XMLHttpRequest:网络错误访问被拒绝

Posted

技术标签:

【中文标题】XMLHttpRequest:网络错误访问被拒绝【英文标题】:XMLHttpRequest: Network Error Access is denied 【发布时间】:2015-01-31 14:10:04 【问题描述】:

我有一个 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】:

好的,我从 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());

【讨论】:

以上是关于XMLHttpRequest:网络错误访问被拒绝的主要内容,如果未能解决你的问题,请参考以下文章

浏览器 11 | Angular 4 - CORS 请求失败(XMLHttpRequest:网络错误 0x80070005,访问被拒绝。)

IE 11 错误 - 访问被拒绝 - XMLHttpRequest

SCRIPT7002:XMLHttpRequest:网络错误 0x80070005,成功预检请求后拒绝访问

XMLHttpRequest:网络错误 0x80070005,在 Microsoft Edge(但不是 IE)上拒绝访问

添加文档访问被拒绝

[XMLHttpRequest访问被拒绝,但试图从Web服务器位置访问文件-IE8