2013-10-24 32 views
13

Ho il seguente metodo:Come ottenere risposta JSON da un servizio Web 3.5 ASMX

using System.Web.Services; 
using System.Web.Script.Services; 
using System.Web.Script.Serialization; 
using Newtonsoft.Json; 
using System.Collections; 

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
//[System.ComponentModel.ToolboxItem(false)] 
[System.Web.Script.Services.ScriptService] 

// [System.Web.Script.Services.ScriptService] 
public class Tripadvisor : System.Web.Services.WebService { 

    public Tripadvisor() { 

     //Uncomment the following line if using designed components 
     //InitializeComponent(); 
    } 


    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string HotelAvailability(string api) 
    { 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     string json = js.Serialize(api); 
     //JsonConvert.SerializeObject(api); 
     return json ; 
    } 

Qui ho impostato l'attributo ResponseFormat è s JSON ancora da restituire in formato XML.

Voglio usare il formato json usando questo servizio asmx Qualche idea?

+0

Possibile duplicato di [Ottieni dati JSON con jQuery da un servizio .NET: confuso con l'installazione ajax] (http://stackoverflow.com/questions/5690882/get-json-data-with-jquery-from-a- net-service-confused-with-ajax-setup) – GSerg

+0

Possibile duplicato di [Asmx web service come restituire JSON e non XML?] (https://stackoverflow.com/questions/14950578/asmx-web-service-how- to-return-json-and-not-xml) –

risposta

40

Ho affrontato lo stesso problema e ho incluso il codice seguente per farlo funzionare.

[WebMethod] 
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)] 
public void HelloWorld() 
{ 
    Context.Response.Clear(); 
    Context.Response.ContentType = "application/json"; 
    Context.Response.Write("Hello World"); 
    //return "Hello World"; 
} 

Aggiornamento:

Per ottenere un formato JSON puro, è possibile utilizzare JavaScript serializzatore come qui di seguito.

public class WebService1 : System.Web.Services.WebService 
{ 
    [WebMethod] 
    [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)] 
    public void HelloWorld() 
    { 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     Context.Response.Clear(); 
     Context.Response.ContentType = "application/json";   
     HelloWorldData data = new HelloWorldData(); 
     data.Message = "HelloWorld"; 
     Context.Response.Write(js.Serialize(data)); 


    } 
} 

public class HelloWorldData 
{ 
    public String Message; 
} 

Tuttavia questo funziona per tipi complessi, ma la stringa non mostra alcuna differenza.

+0

thansk per la riproduzione caro ma non funziona nel mio codice .... – MansinhDodiya

+0

hai provato a rimuovere il ritorno e utilizzare response.write() invece ?? – Saranya

+0

Okey ora mi dà JSON ma non è puro per esempio passo il parametro ABC e restituisce "ABC" ma JSON puro è come {"ABC"} – MansinhDodiya

1

Solo un dubbio. Quando non ricevi una risposta JSON? Perché quando invochi il servizio Web dal client (presumo un browser Web, ad es. Xhr), devi specificare l'intestazione del tipo di contenuto nella richiesta come "application/json; charset = yourcharset".

Credo che la soluzione di cui sopra restituisca sempre json, indipendentemente dal tipo di contenuto specificato dal client. Il framework dotnet asmx consente questo utilizzando il metodo di intestazione del tipo di contenuto, quindi quanto sopra potrebbe essere classificato come un hack, quando è disponibile una soluzione accurata.

domanda simile a Return Json Data from ASMX web service

Questo potrebbe aiutare anche ->http://forums.asp.net/p/1054378/2338982.aspx#2338982

PS: Io parto dal presupposto che si sta utilizzando la versione dotnet 4.

0

Cari lettori futuri: La risposta attualmente accettata non è il modo giusto. Ti lega all'utilizzo dello JavaScriptSerializer e perdi la possibilità di richiedere xml (o addirittura qualsiasi formato di serializzazione che potrebbe presentarsi in futuro). Il "modo giusto" comporta anche meno codice!

Se decorare la vostra classe di servizio con l'attributo [ScriptService] - che si ha - quindi ASP.NET 3.5+ dovrebbe puntate automaticamente la risposta a JSON a condizione che il richieste Ajax chiamata JSON. I suggerimenti per la serializzazione su JSON manualmente sono semplicemente sbagliati, a meno che non si desideri utilizzare un serializzatore diverso come Newtonsoft.

Che stavi vedendo XML suggerisce una delle seguenti opzioni:

  • Non sei richiedendo JSON nella chiamata Ajax - Guarda Forse alcune voci web.config mancano di lavoro codice di esempio riportato di seguito
  • , secondo a una risposta here (disclaimer: non ho la maggior parte di questi in una produzione web.config; solo iniziare a giocare con questi, se non funziona niente altro)

Ecco un semplice esempio di lavoro di un JSON abilitato ASMX servizio Web:

<%@ WebService Language="C#" Class="WebService" %> 
using System; 
using System.Collections.Generic; 
using System.Web.Services; 

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class WebService : System.Web.Services.WebService { 
    [WebMethod] 
    public MyClass Example() 
    { 
     return new MyClass(); 
    } 

    public class MyClass 
    { 
     public string Message { get { return "Hi"; } } 
     public int Number { get { return 123; } } 
     public List<string> List { get { return new List<string> { "Item1", "Item2", "Item3" }; } } 
    } 
} 

Javascript per richiederla ed elaborare la risposta (vedremo semplicemente pop-up un avviso di JS con il messaggio da MyClass.Message): richiesta

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Test</title> 
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.js" type="text/javascript"></script> 
</head> 
<body> 
    <script type="text/javascript"> 
     $.ajax({ 
      type: "POST", 
      url: "WebService.asmx/Example", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      data: "{ }", 
      error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); }, 
      success: function (msg) { 
       alert(msg.d.Message); 
      } 
     }); 
    </script> 
</body> 
</html> 

Http:

POST http://HOST.com/WebService.asmx/Example HTTP/1.1 
Accept: application/json, text/javascript, */*; q=0.01 
Content-Type: application/json; charset=utf-8 
X-Requested-With: XMLHttpRequest 
Referer: http://HOST.com/Test.aspx 
Accept-Language: en-GB,en;q=0.5 
Accept-Encoding: gzip, deflate 
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0) 
Connection: Keep-Alive 
Content-Length: 3 
Host: HOST.com 

{ } 
risposta

HTTP:

HTTP/1.1 200 OK 
Cache-Control: private, max-age=0 
Content-Type: application/json; charset=utf-8 
Server: Microsoft-IIS/8.0 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Tue, 20 Feb 2018 08:36:12 GMT 
Content-Length: 98 

{"d":{"__type":"WebService+MyClass","Message":"Hi","Number":123,"List":["Item1","Item2","Item3"]}} 

Risultato:

"Hi" viene visualizzato un popup JS.