2013-10-24 103 views
13

我有以下方法JSON響應:如何從一個3.5 ASMX Web服務

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 ; 
    } 

這裏我設置ResponseFormat屬性是JSON仍然被作爲XML返回。

我想使用這個asmx服務的json格式 任何想法?

+0

可能的重複[使用jQuery從.NET服務獲取JSON數據:與ajax設置混淆](http://stackoverflow.com/questions/5690882/get-json-data-with-jquery-from-a- net-service-confused-with-ajax-setup) – GSerg

+0

[Asmx web服務如何返回JSON而不是XML?]的可能重複(https://stackoverflow.com/questions/14950578/asmx-web-service-how-回到json-and-not-xml) –

回答

40

我面臨同樣的問題,幷包括下面的代碼來使它工作。

[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"; 
} 

更新:

要得到一個純粹的JSON格式,你可以使用JavaScript串行像下面。

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; 
} 

然而,這適用於複雜的類型,但串不顯示任何差異。

+0

thansk重播親愛的,但它不工作在我的代碼.... – MansinhDodiya

+0

你嘗試刪除返回並使用response.write(),而不是? – Saranya

+0

Okey現在它給我JSON,但不是純粹的例如我傳遞像ABC參數,它返回「ABC」,但純JSON就像{「ABC」} – MansinhDodiya

1

只是一個疑問。你什麼時候沒有收到JSON響應?因爲當你從客戶端調用Web服務時(我假設Web瀏覽器,即xhr),你應該在請求中指定內容類型標題爲「application/json; charset = yourcharset」。

我相信上述解決方案總是返回json,不管從客戶端指定什麼內容類型。 dotnet asmx框架允許使用內容類型的頭部方法,所以當一個簡潔的解決方案可用時,上面可以被歸類爲黑客。

類似的問題在Return Json Data from ASMX web service

這可能也是幫助 - >http://forums.asp.net/p/1054378/2338982.aspx#2338982

PS:我假設你正在使用的dotnet版本4

0

親愛的未來的讀者:目前公認的答案是不正確的方式。它使你使用JavaScriptSerializer,並且你失去了請求xml的能力(或者確實會有將來出現的任何序列化格式)。 「正確的方式」也涉及較少的代碼!

如果你裝飾用[ScriptService]屬性服務類 - 你有 - 然後ASP.NET 3.5 +會自動序列化到JSON響應提供您Ajax調用請求JSON。除非您希望使用不同的序列化程序,例如Newtonsoft,否則手動連續化到JSON的建議是錯誤的。

,你是看到XML提出以下建議之一:

  • 你是不是在你的Ajax調用請求JSON - 請在下面的工作
  • 示例代碼可能是一些web.config中的條目丟失,根據到一個答案 here(免責聲明:我沒有這些在生產 網絡中的大部分。配置;纔開始與這些玩,如果沒有其他作品)

這裏是一個JSON的一個簡單的工作示例啓用ASMX 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來要求它,並處理響應(我們將簡單地彈出一個JS警報從MyClass.Message消息):

<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 

{ } 

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"]}} 

結果:

「您好」 被顯示在一個彈出JS。