在CORS环境中jQuery AJAX调用之间的ASPNET会话

使用VS2012,框架4.5

我有一个简单的webapp只有一个WebService.asmx文件。 运行项目发布了这两个web方法, SetDataGetData ,这里是C#代码:

 [WebService(Namespace = "http://mydomain.com/")] [System.Web.Script.Services.ScriptService] public class WebService: System.Web.Services.WebService { [WebMethod(EnableSession=true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string SetData() { HttpContext.Current.Session["someData"] = "xxxxxxxxx"; return ""; } [WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetData() { if (HttpContext.Current.Session["someData"] == null) return "Session NULL"; else return HttpContext.Current.Session["someData"].ToString(); } } 

web.config设置为启用CORS以及aspNetCompatibilityEnabled以启用会话共享

             

所以项目运行良好。 现在我想从一个简单的HTML页面中使用这两个方法(HTML 不是 ASPNET项目的一部分,只是一个HTML文件……因此是CORS问题)这是HTML代码(为简单起见,省略了HTML标记,但它只是一个空页):

  $(document).ready(function() { //jQuery.support.cors = true; $.ajax({ type: "POST", url: "http://localhost:62776/WebService.asmx/SetData", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert('SetData OK'); $.ajax({ type: "POST", url: "http://localhost:62776/WebService.asmx/GetData", contentType: "application/json; charset=utf-8", dataType: "json", //async: true, -- makes no difference //beforeSend: function(xhr){ // xhr.withCredentials = true; //}, success: function(msg) { alert('GetData: ' + msg.d); }, error: function(e){ alert("GetData: Unavailable"); } }); }, error: function(e){ alert("SetData: Unavailable"); } }); });  

运行HTML页面给我SetData OK然后GetData: Session NULL但我想要GetData: xxxxxx

所以我的问题是,如何在CORS调用之间访问相同的Session Object

我也尝试启用身份validation,认为ASPNET AUTH COOKIES会以某种方式在AJAX调用之间保持正确的会话ID,但它不起作用。 有一种可能的方法使用SOAP信封来validation每个AJAX调用并发送会话信息,但这似乎有点过分。

你需要设置withCredentials,这意味着客户想要发送隐含的“东西”(包括cookie):

http://brockallen.com/2012/12/15/cors-and-windows-authentication/

此外,鉴于您需要允许“凭据”,服务器必须使用具有特定来源请求的Access-Control-Allow-Origin进行响应 – 它不能使用“*”。

您是否尝试过将以下内容添加到web.config文件中?

       

或者在Web方法中添加以下代码:

 [ScriptMethod(UseHttpGet = true)] public string HelloWorld() { return "Hello World"; } 

用这个来打电话给你的服务(javascript):

 function SendAjaxRequest(url) { var xmlhttp = ""; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET", url, false); xmlhttp.onreadystatechange = function () { //when response is ready if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var rspText = xmlhttp.responseText; if (rspText != undefined) { // here is the response var json = JSON.parse(rspText); } } } xmlhttp.send(null); } 

如果你注意到返回的数据将包装在标签中以删除它并只是获取数据使用此function:

 function TrimXmlTag(start, responseText) { var from = responseText.indexOf(start), remaining = responseText.substring(from, responseText.length - 9); return remaining; } 

并只是改变这一行:

  var json = JSON.parse(TrimXmlTag("[",rspText)); 

希望能帮助到你。