1

使用VS2012,框架4.5

我有一个简单的 webapp,只有一个 WebService.asmx 文件。运行该项目会发布这 2 个 Web 方法,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 调用并发送会话信息,但这似乎有点过头了。

4

2 回答 2

1

You need to set withCredentials which means the client wants implicit "stuff" to be sent (which includes cookies):

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

Also, given that you need "credentials" to be allowed, the server must respond with Access-Control-Allow-Origin with the specific origin requesting -- it can't use "*".

于 2013-07-28T05:38:37.283 回答
1

您是否尝试过添加到您的 web.config 文件

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

或将以下代码添加到您的网络方法中:

[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 TrimXmlTag(start, responseText) {

   var from = responseText.indexOf(start),
       remaining = responseText.substring(from, responseText.length - 9);

   return remaining;
}

只需更改此行:

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

希望能帮助到你。

于 2013-08-01T16:44:01.053 回答