Включить междоменный доступ для веб-службы

я хочу разрешить доступ к веб-службе из любого домена, поэтому я исследовал следующее:
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" вместо dataType: "json".
вот мой экран консоли Из браузера Chrome введите здесь описание изображения




введите здесь описание изображения


person user2788596    schedule 17.09.2014    source источник


Ответы (1)


Хорошо, наконец, я нашел, что не так с моим кодом.
я добавляю обратный вызов в URL в вызове javascript Ajax и устанавливаю значение типа данных в 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) { }
    }


person user2788596    schedule 14.10.2014
comment
Нет необходимости добавлять clientaccesspolicy.xml или crossdomain.xml - person user2788596; 21.10.2014
comment
вы используете UseHttpGet = true и в типе вызова ajx: «POST», как это возможно? - person Ganesh Jangam; 12.08.2020