我在asp.net Web api项目中遇到CORS
错误:
访问“ http://abc.xyz.in/api/Sample/loginAPI”处的XMLHttpRequest 来自来源“ http://localhost:8000”的信息已被CORS政策阻止: 对预检请求的响应未通过访问控制检查: 没有HTTP正常状态。
即使我已经正确配置了cors
。这是我的WebApiConfig.cs
:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
我的控制器代码:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[HttpPost]
public IHttpActionResult loginAPI()
{
//code here
}
将此代码添加到Global.asax
文件中:
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
我也在我的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" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
我该如何解决?任何帮助或建议将不胜感激。谢谢!