简体   繁体   English

使用setRequestHeader时,在IIS(ASP.net)上使用CORS的跨站点AJAX失败

[英]Cross-Site AJAX using CORS on IIS (ASP.net) fails when setRequestHeader is used

OK, so I am trying to enable CORS on my ASP.net server so that I can test some javascript against my Web API using jsFiddle. 好的,所以我尝试在ASP.net服务器上启用CORS,以便可以使用jsFiddle针对我的Web API测试一些javascript。 My web forms page calls the EnableCors function (below) on the pageInit event. 我的Web表单页面在pageInit事件上调用EnableCors函数(如下)。

Public Sub EnableCors(Optional Origin As String = "", Optional Methods As String = "", Optional Headers As String = "")
    Response.Headers.Add("Access-Control-Allow-Origin", vbNVL(Origin, "*"))
    Response.Headers.Add("Access-Control-Allow-Methods", vbNVL(Methods, "*"))
    Response.Headers.Add("Access-Control-Allow-Headers", vbNVL(Headers, "*"))
    Response.Headers.Add("Access-Control-Expose-Headers", "Access-Control-Allow-Origin")
End Sub

The vbNVL function simply replaces any empty string with the second parameter value. vbNVL函数仅用第二个参数值替换任何空字符串。 So, the values for the first 3 headers just end up being "*" if no parameters were passed to the Sub. 因此,如果没有参数传递给Sub,则前3个标头的值最终将变为“ *”。

Using my jsFiddle , everything works great until I append header values to the request object, then it fails saying "CORS header 'Access-Control-Allow-Origin' missing". 使用我的jsFiddle ,一切工作都很好,直到我将标头值附加到请求对象,然后它才失败说“ CORS标头'Access-Control-Allow-Origin'missing”。 Please take a look at the fiddle, and toggle setHeaders variable to false on line one to see it succeed. 请看一下小提琴,然后在第一行将setHeaders变量切换为false才能看到成功。 Line 31 is where the variable is being used. 第31行是使用变量的位置。 This is a super simple example. 这是一个非常简单的例子。

Can someone please help me figure out why this fails when I use the setRequestHeader method on the XMLHttpRequest object? 有人可以帮我弄清楚为什么我在XMLHttpRequest对象上使用setRequestHeader方法时失败了吗? Thanks! 谢谢!

Have you tried adding the enableCors attribute to the top of your WebAPI contronller, Ie 您是否尝试过将enableCors属性添加到WebAPI控制程序的顶部,即

[EnableCors(origins: "http://youroriginaddress.com", headers: "*", methods: "*")]

The following tutorial should be of help to you also: 以下教程也应该对您有所帮助:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Let me know how it goes. 让我知道事情的后续。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM