2016-11-11 95 views
2

我在调用Asp.net中的REST Web API时收到以下错误。对预检请求的响应未通过访问控制检查(Angular2)

XMLHttpRequest无法加载http://localhost:54859/api/PostData。对预检请求的响应不会通过访问控制检查:请求的资源上不存在“访问控制 - 允许来源”标头。因此不允许访问原产地'http://localhost:3000'。

我使用Angular2作为前端。在后端,我添加了以下代码以在WEB API中启用CORS。

var corsAttr = new EnableCorsAttribute("*", "*", "*"); 
config.EnableCors(corsAttr); 

一切为了HTTP GET请求工作正常,但不能用于HTTP POST请求的相同。

任何帮助将是明显的

提前感谢!

回答

2

我通过向web.config添加以下行来解决问题。

<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"> 
    </modules> 
</system.webServer> 

谢谢。

3

增加对预检要求Access-Control-Allow-Origin头的Application_BeginRequest在Global.asax.cs中在为我工作。

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头。

相关问题