jQuery的AJAX之间ASPNET会议在CORS环境要求 [英] ASPNET Session between jQuery AJAX calls in a CORS enviroment

查看:86
本文介绍了jQuery的AJAX之间ASPNET会议在CORS环境要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VS2012,框架4.5

Using VS2012, framework 4.5

我只是一个WebService.asmx文件的简单Web应用程序。运行项目发布以上2 webMethods的,的SetData 的GetData ,这里的C#code:

I have a simple webapp with just a WebService.asmx file. Running the project publishes these 2 webmethods, SetData and GetData, here's the C# code:

[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页面这2种方法(该HTML是不会的ASPNET项目的一部分,仅仅是一个HTML文件...因此CORS的问题)
这里的HTML code(左出简单的HTML标签,但它只是一个空白页):

So the projects runs fine. Now I want to consume these 2 methods from a simple HTML page (the HTML is NOT part of the ASPNET project, is just an HTML file... thus the CORS problem) Here's the HTML code (left out the HTML tags for simplicity, but it's just an empty page):

<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确定然后的GetData:会话NULL ,但我想的 的GetData:XXXXXX

Running the HTML pages gives me SetData OK and then GetData: Session NULL but I want GetData: xxxxxx

所以我的问题是,我怎么能访问相同的 Session对象之间CORS电话?

So my question is, how can I access the same Session Object between CORS calls?

我也试过启用身份验证,认为ASPNET AUTH COOKIES会以某种方式保持正确的会话ID之间的AJAX调用,但没有奏效。有使用SOAP信封来验证每一个AJAX调用发送会话信息一种可能的方法,但似乎矫枉过正。

I also tried enabling authentication, thinking that ASPNET AUTH COOKIES will somehow keep the correct session ID between AJAX calls, but it didn't work. There is a possible approach using SOAP envelopes to authenticate each AJAX call and send session info, but that seems overkill.

推荐答案

你试过以下添加到您的web.config文件

have you tried following adding to your web.config file

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

或添加以下code到Web方式:

or add following code to your web method:

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

使用这个来调用服务(JavaScript的):

use this to call your service (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);
}

如果您发现返回的数据将是标签包装将其删除,只是获取数据使用此功能:

if you notice the returned data would be wrap in tag to remove it and just get the data use this 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));

希望它帮助。

这篇关于jQuery的AJAX之间ASPNET会议在CORS环境要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆