2014-12-03 243 views
1

我有一個MVC 4應用程序使用角度向Web API應用程序發送http POSTS請求。一切正常的發展環境符合市場預期,但在部署到我們的生產環境我得到下面的錯誤在瀏覽器中XMLHttpRequest:網絡錯誤訪問被拒絕

XMLHttpRequest: Network Error 0x80070005, Access is denied. 

這看起來像一個CORS問題的控制檯日誌,我添加以下代碼我的web.config

<system.webServer> 
<handlers> 
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
    <remove name="OPTIONSVerbHandler" /> 
    <remove name="TRACEVerbHandler" /> 
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
</handlers> 
<httpProtocol> 
    <customHeaders> 
    <clear /> 
    <add name="Access-Control-Allow-Origin" value="*" /> 
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" /> 
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /> 
    </customHeaders> 
</httpProtocol> 

跟着Enabling Cross-Origin Requests in ASP.NET Web API 2無濟於事。還有什麼我失蹤?

回答

1

好吧,我從我的web.config

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

刪除下面的代碼,並寫了一個定製CORS策略屬性類爲我的網頁API

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] 
public class CrestCorsPolicyAttribute : Attribute, ICorsPolicyProvider 
{ 
    private readonly CorsPolicy _policy; 

    public CrestCorsPolicyAttribute() 
    { 
     _policy = new CorsPolicy 
     { 
      AllowAnyMethod = true, 
      AllowAnyHeader = true 
     }; 

     var allowedOrigins = ConfigurationManager.AppSettings["AllowedOrigins"].Split(','); 
     foreach (var allowedOrigin in allowedOrigins) 
     { 
      _policy.Origins.Add(allowedOrigin); 
     } 
    } 

    public Task<CorsPolicy> GetCorsPolicyAsync 
     (
     HttpRequestMessage request, 
     CancellationToken cancellationToken 
     ) 
    { 
     return Task.FromResult(_policy); 
    } 
} 

這是我從我的Global.asax實施文件

GlobalConfiguration.Configuration.EnableCors(new CrestCorsPolicyAttribute());