【问题标题】:Enable cross domain acess for web service为 Web 服务启用跨域访问
【发布时间】:2014-11-11 11:17:48
【问题描述】:

我想启用任何域都可以访问 Web 服务,所以我研究了以下内容
clientaccesspolicy.xml

<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>


crossdomain.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<?xml version="1.0" ?>
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
  <allow-access-from domain="*" />
</cross-domain-policy>


在我的 web.config 中,我添加了以下内容

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol> 

我已经一个一个地使用了这两个文件并且同时使用了这两个文件。仍然无法从其他域请求。
这是 jquery 代码

           var cid="My String Input";
           var webMethod = "MyWemMethodUrl";
           var parameters = "{'ContactID':'" + cid + "'}";

           $.ajax({
               type: "POST",
               url: webMethod,
               data: parameters,
               async: false,
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (result) {
                   debugger;
                   var _JSONObj = jQuery.parseJSON(result.d);
                   if (_JSONObj.StatusCode == "0") {
                       alert("Error");
                   }
                   else {
                       alert("Success");
                   }
               },
               error: function (jqXHR, exception, thrownError) {
                   debugger;
                   if (jqXHR.status === 0) {
                       alert('Not connected.\nPlease verify your network connection.');
                   } else if (jqXHR.status == 404) {
                       alert('The requested page not found. [404]');
                   } else if (jqXHR.status == 500) {
                       alert('Internal Server Error [500].');
                   } else if (exception === 'parsererror') {
                       alert('Requested JSON parse failed.');
                   } else if (exception === 'timeout') {
                       alert('Time out error.');
                   } else if (exception === 'abort') {
                       alert('Ajax request aborted.');
                   } else {
                       alert('Uncaught Error.\n' + jqXHR.responseText);
                   }
               }
           });

它总是出错 jqXHR.status=0 路径
甚至我尝试了 dataType: "jsonp" instread of dataType: "json"。
这是我的控制台屏幕来自 Chrome 浏览器




【问题讨论】:

    标签: jquery asp.net cross-domain cross-domain-policy


    【解决方案1】:

    好吧,我终于发现我的代码出了什么问题。
    我在 javascript Ajax 调用的 url 中添加回调并将数据类型值设置为 jsonp


            $.ajax({
            type: "POST",
            url: WebMethod+'?callback=jsonCallback',
            crossDomain: true,
            contentType: "application/json; charset=utf-8",    
            data: parameters,
            dataType: "jsonp",
            jsonpCallback: 'jsonCallback',
            success: function (result) {
                 /*SUCCESS CODE*/
            },
            error: function (jqXHR, exception, thrownError) {
    
               /*error Code*/
            }
    
    });
    


    而不是字符串返回类型函数,我改为使用 void 的非返回类型。

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
     public void WebMethod()
        {
           String ReponseResult = "";/*Json String that i want to return*/
            /*My Code and logic
    
               ----
    
             */
        /*To return Json String  I added following Code*/
      try
        {
    
    
            string callback = HttpContext.Current.Request.Params["callback"];
            string json = ReponseResult;
            string response1 = string.IsNullOrEmpty(callback) ? json : string.Format("{0}({1});", callback, json);
    
            // Response
            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.Write(response1);
        }
        catch (Exception ex) { }
        }
    


    【讨论】:

    • 无需添加clientaccesspolicy.xml或crossdomain.xml
    • 你使用 UseHttpGet = true 并且在 ajx 调用类型中:'POST',这怎么可能?
    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 2014-12-07
    • 2015-08-22
    • 2011-12-03
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多