2015-12-31 63 views
1

我正在运行使用AngularJS的小型Web应用程序,运行在IIS8.5服务器上,并使用DreamFactory作为API。尝试在服务中创建$ http请求时,我遇到了CORS问题。CORS自定义头文件

错误不断提示Access.Control-Allow-Headers值在web.config文件中为空;然而,事实并非如此。

尝试发送API请求时收到此错误:“预检响应中的请求标头字段内容类型不被Access-Control-Allow-Headers所允许。当头文件请求中没有注释的时候,我也会得到错误中列出的X-DreamFactory-API-Key。

我的$ HTTP调用看起来是这样的:

$http({ 
        method: 'POST', 
        headers: { 
         'X-DreamFactory-API-Key':'apiKey' 
        },... 

我的web.config文件有:

<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Origin, X-Requested-With, X-DreamFactory-API-Key" /> <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" /> <add name="Access-Control-Allow-Credentials" value="true" /> </customHeaders> </httpProtocol>

这是在根级别的配置,一直推到网站级别。

我也在Dreamfactory管理控制台中设置了CORS。

有没有人有任何线索,发生了什么,以及如何解决这个问题?谢谢。

回答

1

正如您已经意识到的那样,ASP.NET中的飞行前CORS不能很好地工作。我没有使用DreamFactory,而且我在IIS 7.5上,但是,最有可能适用。

我使用自定义的HttpModule解决了这个问题。

public class CorsModule : IHttpModule 
{ 
    public void Dispose() { 
     // There's nothing to dispose here, but the dispose implementation is required. 
    } 

    public void Init(HttpApplication context) 
    { 
     if (context == null) 
     { 
      throw new ArgumentNullException("context"); 
     } 

     // Without this .NET sends a weird status code, can't remember what exactly. 
     context.PreSendRequestHeaders += delegate 
     { 
      if (context.Request.HttpMethod == "OPTIONS") 
      { 
       var response = context.Response; 
       response.StatusCode = (int)HttpStatusCode.OK; 
      } 
     }; 

     // Bind to the Application_BeginRequest event. This is the important part right here. 
     context.BeginRequest += this.Application_BeginRequest; 
    } 

    private void Application_BeginRequest(Object source, EventArgs e) 
    { 
     // Personally I only needed to send those headers in the OPTIONS method. 
     // You might need to change this for your needs. 
     if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
     { 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Origin, Content-Type, Accept, X-Requested-With, SOAPAction"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
      HttpContext.Current.Response.End(); 
     } 
    } 

,我需要在我的web.config的唯一的事情就是Access-Control-Allow-OriginAccess-Control-Allow-Credentials和我的HttpModule参考:

<modules> 
    <add name="CorsModule" type="MyNamespace.CorsModule, MyAssembly" /> 
</modules>