2012-09-28 25 views
6

Bu konu, daha karışık sonuçlarla bir milyon "çözüm" ile bir tane gibi görünüyor. Bu yüzden, neler olup bittiğini, ne kullandığımı ve sorunu nasıl çözmeyi denediğimi göstermeye çalışacağım için lütfen bana biraz gevşeklik katın.asmx web hizmeti - jQuery ajax gönderi jsonu (500 hatası) - CORS (Erişim-Kontrol-İzin-Kökeni * olarak ayarlanmış)

Benim test ortamı IIS6 asp.net 2.0 çalıştıran, ben de jQuery v1 aracılığıyla

"GET,HEAD,POST,DEBUG,OPTIONS" 

için .asmx uzantıları için fiilleri belirledik

'Access-Control-Allow-Origin' * 

ile kurdunuz. 7.2 ajax() çağrıları, xml dosyalarını şundan GET yapabildiğimi ve POST'un beklenen sonuçları çapraz etki alanına sahip bir dize döndüren temel bir hizmete gönderebildiğimi gösterir. Bu yüzden, en azından kısmen etki alanları arası isteklerin çalıştığını biliyorum.

Bu konuda genişletmek ve hizmet veri göndermek için json kullanmaya başladığınızda My sorunu da ortaya çıkıyor

ben basit asmx webcoder yöntemi vardır:

 [WebMethod] 
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
     public SubResponse HelloWorldX(SubRequestXX SubReq) 
     { 
      SubResponse sr = new SubResponse(); 

      sr.resultCode = "777"; 
      sr.resultMsg = "hello - " + SubReq.EmailAddress; 

      return sr; 
     } 

Çok basit ve çok değil sihirli orada olmak, tek yapmak istediğim 'SubRequestXX' nesnesini geçmek, ve şimdi sadece oraya var olduğunu ve cevap verdiğini doğrulamak.

Using jQuery: 

    $.ajax({ 
     type: "POST", 
     url: "http://somedomain/subscription/MyService.asmx/HelloWorldX", 
     processData: false, 
     data: '{ "SubReq" : {"EmailAddress":"[email protected]"} }', 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     cache: false, 
     success: function(data, textStatus, jqXHR) { 
      ajaxSucccess3(data, textStatus, jqXHR); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log("Retrieve Hello Failed (AJAX Error): " + jqXHR.statusText + " | " + textStatus + " | " + errorThrown); 
     } 
    }); 
} 

Belki de cevap orada mıdır? ama burada kemancının RAW veri aynı etki alanında bir sayfadan tam aynı JS kodu kullanarak bana gösteriyor ne (başarılı - sonuç kodu 200):

REQUEST: 
    POST http://somedomain/subscription/Service.asmx/HelloWorldX HTTP/1.1 
    Accept: application/json, text/javascript, */*; q=0.01 
    Content-Type: application/json; charset=utf-8 
    X-Requested-With: XMLHttpRequest 
    Referer: http://somedomain/subscription/subscription_-cors.html 
    Accept-Language: en-us 
    Accept-Encoding: gzip, deflate 
    User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; 9LA) 
    Host: somedomain 
    Content-Length: 45 
    Connection: Keep-Alive 
    Pragma: no-cache 

    { "SubReq" : {"EmailAddress":"[email protected]"} } 

RESPONSE: 

    HTTP/1.1 200 OK 
    Date: Fri, 28 Sep 2012 16:59:15 GMT 
    Server: Microsoft-IIS/6.0 
    X-Powered-By: ASP.NET 
    Access-Control-Allow-Origin: * 
    X-AspNet-Version: 2.0.50727 
    Cache-Control: private, max-age=0 
    Content-Type: application/json; charset=utf-8 
    Content-Length: 147 

    {"d":{"__type":"SubService.DataObj.SubResponse","resultCode":"777","resultMsg":"hello - [email protected]"}} 

Yani her şey harika görünüyor ve beklendiği gibi davranır. Aynı html/js kodu, başka bir sunucuda dağıtmak ve aynı talebi (siteler arası) kemancı gösterileri yapmak alırsak Şimdi (sonuç kodu 500 başarısız):

REQUEST: 
    POST http://somedomain/subscription/Service.asmx/HelloWorldX HTTP/1.1 
    Accept: */* 
    Origin: http://www.crossdomainsite.com 
    Accept-Language: en-US 
    Accept-Encoding: gzip, deflate 
    User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; 9LA) 
    Host: somedomain 
    Content-Length: 0 
    Connection: Keep-Alive 
    Pragma: no-cache 


RESPONSE: 
HTTP/1.1 500 Internal Server Error 
Date: Fri, 28 Sep 2012 16:58:56 GMT 
Server: Microsoft-IIS/6.0 
X-Powered-By: ASP.NET 
Access-Control-Allow-Origin: * 
X-AspNet-Version: 2.0.50727 
Cache-Control: private 
Content-Type: text/html; charset=utf-8 
Content-Length: 4732 

..... 

Request format is unrecognized for URL unexpectedly ending in '/HelloWorldX' 

..... 

[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/HelloWorldX'.] 
    System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +405961 
    System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212 
    System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47 
    System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +193 
    System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +93 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 

Birçok arama sonuçları, web birkaç düşündürmektedir. yapılandırma değişiklikleri. Ben eklersem system.web bölümüne aşağıdaki:

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

sonra benim isteği

POST http://somedomain/subscription/Service.asmx/HelloWorldX HTTP/1.1 
Accept: */* 
Origin: http://www.crossdomainsite.ca 
Accept-Language: en-US 
Accept-Encoding: gzip, deflate 
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; 9LA) 
Host: somedomain 
Content-Length: 0 
Connection: Keep-Alive 
Pragma: no-cache 

Ve YANIT gibi görünür:

HTTP/1.1 500 Internal Server Error 
Date: Fri, 28 Sep 2012 17:37:00 GMT 
Server: Microsoft-IIS/6.0 
X-Powered-By: ASP.NET 
Access-Control-Allow-Origin: * 
X-AspNet-Version: 2.0.50727 
Cache-Control: private 
Content-Type: text/plain; charset=utf-8 
Content-Length: 461 

System.InvalidOperationException: HelloWorldX Web Service method name is not valid. 
    at System.Web.Services.Protocols.HttpServerProtocol.Initialize() 
    at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) 
    at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing) 

Yani benim web bölümde belirtti. Yapılandırma sonuçlardan biraz farklı olduğu için bir şey yaptı. Ama ne olduğunu ayırt edemiyorum.

Diğer çözümler ben asp.net 2.0 kullanıyorum, çünkü bu web yapılandırma ayarları önermek tüm Yukarıdaki sonuçlardan sırasında gösterilen gibi olanları proje yaratma orijinalleridir dışarı yorumladı, bu bırakmış not: Yani

 <httpHandlers> 
      <remove verb="*" path="*.asmx"/> 
      <!--<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>--> 
      <add path="*.asmx" verb="*" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 

      <!--<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>--> 
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 

      <!--<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>--> 
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> 
     </httpHandlers> 

... Büyük Soru ... Yukarıdaki tüm nedenlere rağmen siteler arası taleplerim aynı kodla neden başarısız oluyor? İstek JSON üzerinde boğulduğu başka bir alandan gelir gelmez gibi görünüyor.

Bu gizemi çözmek için herhangi bir yardım büyük ölçüde takdir edilecektir. Onun bir IIS6 (sunucu) ayarı veya $ değerinde olduğunu varsayalım.ajax() çağrısı ve kendimi muhtemelen basit ya da küçük bir şey gibi hissediyorum, ama parmağımı üzerine koyamıyorum.

cevap

0

JSONP ile simil bir şey denedim. Sanırım çözümü bu makaleden aldım.

JSONP + CORS

diğer potansiyel şey WCF hizmetine bir dize olarak JSON koyarak tipik (Sadece aynı sorun olabilir söyleyerek bu WCF değil biliyorum) iyi bitmiyor olmasıdır.

Using jQuery: 

$.ajax({ 
    type: "POST", 
    url: "http://somedomain/subscription/MyService.asmx/HelloWorldX", 
    processData: false, 
    data: JSON.parse('{ "SubReq" : {"EmailAddress":"[email protected]"} }'), 
    dataType: "json", 
    contentType: "application/json; charset=utf-8", 
    cache: false, 
    success: function(data, textStatus, jqXHR) { 
     ajaxSucccess3(data, textStatus, jqXHR); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.log("Retrieve Hello Failed (AJAX Error): " + jqXHR.statusText + " | " + textStatus + " | " + errorThrown); 
    } 
}); 
} 

JSON.parse kullanımı da geçer herhangi kötü JSON yakalayacak: Bunu genelde.

Bu sorununuzu düzeltir umuyoruz.