Jay*_*der 10 c# asp.net asp.net-web-api asp.net-web-api2 angular
我在Asp.net中调用REST Web API时遇到错误.
XMLHttpRequest无法加载http:// localhost:54859/api/PostData.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:3000 '访问.
我使用Angular2作为前端.在后端,我添加了以下代码以在WEB API中启用CORS.
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
Run Code Online (Sandbox Code Playgroud)
一切都适用于Http get请求,但同样不适用于Http Post请求.
任何帮助都会很明显
提前致谢!
Jay*_*der 13
我通过在web.config中添加以下行来解决它.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
谢谢.
小智 7
Access-Control-Allow-Origin在Global.asax.cs中的Application_BeginRequest期间为预检请求添加标头对我有用.
Global.asax/Global.asax.cs
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Preflight request comes with HttpMethod OPTIONS
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
// The following line solves the error message
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
// If any http headers are shown in preflight error in browser console add them below
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
Run Code Online (Sandbox Code Playgroud)
解决此问题后,应用程序在浏览器控制台上抛出了错误,即在预检响应中未提及某些标头.
将标题添加到Access-Control-Allow-Headers预检响应的标题后,它就会得到解决.
| 归档时间: |
|
| 查看次数: |
14075 次 |
| 最近记录: |