WebSite下创建webapi

注意这里说的是WebSite,不是Webapp

就是我们常说的新建网站,而不是新建项目

直接上代码:


1 在要在website下创建,那么应该这么干。
先添加引用和global.asax


然后创建对应的路由文件和apicontroller。
他们必须创建在app_code文件夹里。这是website的规则


然后看一下  各个文件的配置
Global.asax(HelloWebAPI是我路由的namespace)

C# code
?
1
2
3
4
5
6
void Application_Start(object sender, EventArgs e) 
    {
        // 在应用程序启动时运行的代码
        HelloWebAPI.WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
        HelloWebAPI.FilterConfig.RegisterGlobalFilters(System.Web.Mvc.GlobalFilters.Filters);
    }


WebApiConfig
C# code
?
1
2
3
4
5
6
7
8
9
10
11
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }


ValuesController
C# code
?
1
2
3
4
public IEnumerable<string> Get()
    {
        return new string[] { "value1""value2" };
    }


最后看一下效果


原文地址:https://www.cnblogs.com/hanjun0612/p/9779833.html