2012-01-16 17 views
5

Il mio problema è noto e discusso here e here. Ma anche dopo aver letto e implementato le soluzioni suggerite non sono in grado di farlo funzionare.chiamata interdominio con jQuery jsonp al servizio Web ASP.NET

Il problema: il servizio web di ritorno xml invece di JSON:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string> 

Ora lascia rompere il codice in sezioni:

server remoto (IIS 7.0, .NET 4):
web.config:

<?xml version="1.0"?> 
<configuration> 
     <system.webServer> 
      <modules> 
       <add name="JsonHttpModule.JsonHttpModule" type="JsonHttpModule"/> 
      </modules> 
     </system.webServer> 
    <system.web.extensions> 
     <scripting> 
      <webServices> 
       <jsonSerialization maxJsonLength="102400"/> 
      </webServices> 
     </scripting> 
    </system.web.extensions> 
    <system.web> 
     <compilation debug="true" targetFramework="4.0" /> 
     <customErrors mode="Off"/> 
     <webServices> 
      <protocols> 
       <add name="HttpGet"/> 
       <add name="HttpPost"/> 
      </protocols> 
     </webServices> 
    </system.web> 
</configuration> 


servizio web:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Services; 
using JsonHttpModule; 
/// <summary> 
/// Summary description for JSONP_EndPoint 
/// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class MyService : System.Web.Services.WebService { 
    [WebMethod] 
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
    public string Sum(string x, string y) 
    { 
     return x + y; 
    } 

} 


classe HttpModule:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.IO; 
using System.Text; 

/// <summary> 
/// Summary description for ContentTypeHttpModule 
/// </summary> 
namespace JsonHttpModule 
{ 
    public class JsonHttpModule : IHttpModule 
    { 
     private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8"; 

     public void Dispose() 
     { 
     } 
     public void Init(HttpApplication app) 
     { 
      app.BeginRequest += OnBeginRequest; 
      app.EndRequest += new EventHandler(OnEndRequest); 
     } 
     public void OnBeginRequest(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 
      HttpRequest request = app.Request; 
      //Make sure we only apply to our Web Service 
      if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx")) 
      { 
       if (string.IsNullOrEmpty(app.Context.Request.ContentType)) 
       { 
        app.Context.Request.ContentType = JSON_CONTENT_TYPE; 
       } 
       app.Context.Response.Write(app.Context.Request.Params["callback"] + "("); 
      } 
     } 
     void OnEndRequest(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 
      HttpRequest request = app.Request; 
      if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx")) 
      { 
       app.Context.Response.Write(")"); 
      } 
     } 
    } 
} 

lato client (localhost):

<script> 
    $(function() { 
     $('#btn_test').click(function() { 
      $.ajax({ url: "http://tonofweb.com/MyService.asmx/Sum", 
       data: { x: JSON.stringify("Now i am getting jsop string"), y: JSON.stringify("2nd param") }, 
       dataType: "jsonp", 
       success: function (json) { 
        alert(json.d); 
       }, 
       error: function() { 
        alert("Hit error fn!"); 
       } 
      }); 
    }); 
}); 
</script> 
    <input id="btn_test" type="button" value="POST" /> 

quindi cosa sto facendo di sbagliato qui? puoi testarlo da soli, è un servizio web in diretta. Grazie per il vostro aiuto.

+0

passaggio da jsonp a JSON non funziona a causa di croce problema dominio e la conversione di opporsi ancora tornare xml –

risposta

7

Sembra che tutta la configurazione e gli attributi siano presenti per il servizio Web per restituire JSON ma ho notato nella richiesta jQuery, non si specifica il tipo di contenuto dei dati che si stanno passando. L'ho aggiunto a il codice qui sotto:

$.ajax({ 
    url: "http://tonofweb.com/MyService.asmx/Sum", 
    contentType: "application/json; charset=utf-8", 
    data: { x: JSON.stringify("1"), y: JSON.stringify("2") }, 
    dataType: "jsonp", 
    success: function (json) { 
    alert(json.d); 
    }, 
    error: function() { 
    alert("Hit error fn!"); 
    } 
}); 

Avviso ho aggiunto contentType: "application/json; charset=utf-8", alle impostazioni di richiesta.

Ho testato questo codice si naviga a http://tonofweb.com (che restituisce un 403 al momento), tra cui jQuery utilizzando il jQuerify bookmarklet, e quindi eseguire il codice dalla tua domanda prima (senza il contentType), e quindi il codice Ho pubblicato sopra (con il contentType).

Qui ci sono le risposte dalla scheda di rete nella Developer Tools Chrome:

Senza contentType:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string> 

Con contentType:

{"d":"12"} 

Così la seconda almeno i risultati in JSON restituiti dal server. Quindi, a parità di tutti gli altri, direi aggiungere il contentType.

Vedi qui per una spiegazione dei requisiti per tornare JSON:

ASMX and JSON – Common mistakes and misconceptions

La richiesta HTTP deve dichiarare un tipo di contenuto application/json. Questo informa lo ScriptService che riceverà i suoi parametri come JSON e che dovrebbe rispondere in natura.

Ora avete ancora un altro problema, e cioè che la richiesta, al termine, chiama la funzione di errore. Se cambi dataType: "jsonp" a dataType: "json" chiamerà la funzione di successo. Quindi qualcosa sulla tua implementazione del wrapper di callback è sbagliato, perché jQuery non può gestire la risposta come JSONP.

Ora io non sto vedendo la richiamata avvolto nella risposta sia, per JSONP, la risposta dovrebbe essere qualcosa di simile:

jQuery17106476630216930062_1326752446188({"d":"12"}) 

Ho notato che si collega a this post su come fare una risposta da JSONP un servizio web, ma non stai seguendo il consiglio: non usi Response.Filter, invece usi Response.Write.

+0

ancora non funziona .... –

+0

Sì, si sta lavorando, lei ha dichiarato: "Il problema: il servizio web XML ritorno istato di json: ". Ho appena testato questo codice e il tuo servizio web risponde con JSON se aggiungi solo "contentType:" application/json; charset = utf-8 "' –

+1

non riesco ancora a farlo funzionare anche dopo aver aggiunto contentType: "applicazione/json; charset = utf-8 "sto ottenendo: " 1 "" 2 "

Problemi correlati