C# 对飞行前请求的响应不';t通过访问控制检查(Angular2)
我在Asp.net中调用RESTWebAPI时遇到以下错误 XMLHttpRequest无法加载。对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许对源“”进行访问。 我使用Angular2作为前端。在后端,我添加了以下代码以在WebAPI中启用CORSC# 对飞行前请求的响应不';t通过访问控制检查(Angular2),c#,asp.net,angular,asp.net-web-api,asp.net-web-api2,C#,Asp.net,Angular,Asp.net Web Api,Asp.net Web Api2,我在Asp.net中调用RESTWebAPI时遇到以下错误 XMLHttpRequest无法加载。对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。因此,不允许对源“”进行访问。 我使用Angular2作为前端。在后端,我添加了以下代码以在WebAPI中启用CORS var corsAttr = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(corsAttr); 对于Http get请求,
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
对于Http get请求,一切都正常,但对于Http Post请求,情况并非如此
任何帮助都是值得的
提前谢谢 我通过在web.config中添加以下行解决了这个问题
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
谢谢。在Global.asax.cs中添加
Access Control Allow Origin
应用程序启动请求期间的飞行前请求标头对我有效
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();
}
}
解决此问题后,应用程序在浏览器控制台上抛出错误,在飞行前响应中未提及某些标头
一旦将标题添加到飞行前响应的Access Control Allow headers
标题中,它就得到了解决
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Preflight request comes with HttpMethod OPTIONS
// The following line solves the error message
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
// 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();
}
}
上面的代码工作得很好谢谢,heaps,在我的例子中,我只需要allow头,因为using*失败了!所以我只是将这个
添加到web.config