Install-Package
Microsoft.AspNet.WebApi.Cors
在WebApiConfig中启用Cors。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.EnableCors();
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
需要引入命名空间:
using System.Web.Http.Cors;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
需要引入命名空间:
using System.Web.Http.Cors;
[EnableCors(origins: "*",headers:"*",methods:"*")]
public class ValuesController1 : ApiController
{
public string Get(int id)
{
return "value";
}
}