根据 asp.net tutorial ,我们只需要以下代码即可在 Web Api
应用程序上启用 cors:
var cors = new EnableCorsAttribute("*","*", "*");
config.EnableCors(cors);
以下是我的代码:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*","*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
它对 Get
工作正常,但对 Post
请求仍然出错
错误如下,我正在上Post:
POST http://api.example.com/token 404 (Not Found) XMLHttpRequest cannot load http://api.example.com/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.example.com' is therefore not allowed access. The response had HTTP status code 404.
最佳答案
您需要将以下内容添加到您的 Web.Config 中:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
System.webServer 配置节点内部。
关于c# - Web Api 2 CORS 不适用于 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32187006/