XMLHttpRequest:网络错误访问被拒绝

时间:2014-12-03 05:44:59

标签: c# asp.net-mvc cors asp.net-web-api

我有一个MVC 4应用程序使用angular向Web API应用程序发出http POSTS请求。一切都在开发环境中按预期工作,但当部署到我们的生产环境时,我在浏览器的控制台日志中收到以下错误

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 个答案:

答案 0 :(得分: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>

并为我的web api

编写了一个自定义CORS策略属性类
[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());