javascript - 跨域调用错误: XMLHttpRequest: Network Error 0x80070005, 访问被拒绝

标签 javascript asp.net-mvc xmlhttprequest cors networkcredentials

使用 MVC Asp.Net

下面的代码适用于实际的用户名和密码。但我不想使用它。 :

WebClient client1 = new WebClient();
client1.Credentials = new NetworkCredential("actualUserName", "actualPassword");
string code1 = client1.DownloadString(@"http://Domainname/GetValue");

尝试了 javascript 方法:

 $.ajax({
    type: 'POST',
    url: Url,
    processData: false,
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    crossDomain: true,
    jsonpCallback: 'CallBackMethod',
    success: function (json) {
        console.log(json); 
    },
    error: function (xhr, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

但出现以下错误:

Multiple Access-Control-Allow-Origin headers are not allowed for CORS response.
XMLHttpRequest: Network Error 0x80070005, Access is denied.

尝试在 Application_BeginRequest 中的 Global.asax 中添加 header 以及在 webconfig 中添加类似条目:

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    HttpContext.Current.Response.End();
}

以上均已尝试,在Win7机器上不起作用。但可以在Win10机器上使用!还尝试在服务器中部署并检查,但弹出相同的错误。

最佳答案

问题的关键就在错误消息中:

Multiple Access-Control-Allow-Origin headers are not allowed

服务器正在响应重复的 header 。这导致某些浏览器失败。您提到您在两个地方实现了 CORS。这是一个很好的起点。删除一个实现,看看会发生什么。

也有一些框架可以实现 CORS。最重要的是,您只需要一种,而且是一种效果最好的。无论您保留什么实现,它都需要处理标准请求和预检请求(选项)。

关于javascript - 跨域调用错误: XMLHttpRequest: Network Error 0x80070005, 访问被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46923037/

相关文章:

javascript - 如何在 MVC 4 razor html url 操作中访问 JavaScript 函数的字符串输出?

asp.net-mvc - 从 ASP.NET MVC 中动态添加的控件获取发布值

javascript - IE 通过 AJAX 调用抛出 "Unspecified Error"?

javascript - 如何在多个文件之间共享全局变量?

javascript - 是否有可能从 xml 中读取每个节点

asp.net-mvc - Rhino.Security : second-level cache is never hit for DetachedCriteria

javascript - 将 Ajax 与 Cookie 结合使用

security - 浏览器API为什么要限制跨域请求?

javascript - CSS HTML : Is there workaround for parent scaling and child position:fixed?

javascript - Jade 中列出的脚本在我的 JavaScript 中无法访问