使用VS2012,框架4.5jQuery的AJAX之間ASPNET會議呼籲在CORS環境
我有一個簡單的Web應用程序,只需WebService.asmx文件。運行該項目公佈這些2個webMethods的,SetData
和GetData
,這裏的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
啓用會話共享
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="null" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
所以項目運行良好。現在我想從一個簡單的HTML頁面中使用這兩種方法(HTML是不是 ASPNET項目的一部分,僅僅是一個HTML文件...因此是CORS問題) 這裏是HTML代碼(省略HTML代碼爲了簡單,但它只是一個空白頁):
<script type="text/javascript">
$(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");
}
});
});
</script>
運行HTML頁面給我SetData OK
然後GetData: Session NULL
,但我想GetData: xxxxxx
所以我的問題是,我怎麼能訪問相同的Session Object
在CORS呼叫之間?
我也嘗試啓用身份驗證,認爲ASPNET AUTH COOKIES會以某種方式保持AJAX調用之間正確的會話ID,但它不起作用。有一種使用SOAP信封來驗證每個AJAX調用併發送會話信息的可能方法,但這看起來過度。
你看過IRequireSessionState嗎? http://msdn.microsoft.com/en-us/library/system.web.sessionstate.irequiressessionstate.aspx –