2011-12-18 101 views
9

我想在我的Web服務方法中將JSON數據返回給客戶端。一種方法是創建SoapExtension這裏使用它作爲屬性在我的網頁的方法,等等。另一種方法是簡單地[ScriptService]屬性添加到Web服務,並讓.NET框架返回的結果爲{"d": "something"} JSON,返回給用戶(d被我控制的東西)。不過,我想回到類似:WebService中的Response.Write()

{"message": "action was successful!"} 

最簡單的方法,可以像編寫一個Web方法:

[WebMethod] 
public static void StopSite(int siteId) 
{ 
    HttpResponse response = HttpContext.Current.Response; 
    try 
    { 
     // Doing something here 
     response.Write("{{\"message\": \"action was successful!\"}}"); 
    } 
    catch (Exception ex) 
    { 
     response.StatusCode = 500; 
     response.Write("{{\"message\": \"action failed!\"}}"); 
    } 
} 

這樣一來,我會得到在客戶端:

{ "message": "action was successful!"} { "d": null} 

這意味着ASP.NET將其成功結果追加到我的JSON結果中。如果在另一方面,我寫了成功的消息,(如response.Flush();)後刷新響應,發生異常時,說:

服務器無法HTTP標頭後明確頭部已經發送。

那麼,怎樣才能得到我的JSON結果,而不改變方法?

+0

嘗試設置response.BufferOutput = TRUE; – 2012-08-23 10:15:50

回答

2

你爲什麼不返回一個對象,然後在客戶端可以調用爲response.d

我不知道你是如何調用您的Web服務,但我做出了榜樣做一些假設:

我使用jQuery AJAX

function Test(a) { 

       $.ajax({ 
        type: "POST", 
        contentType: "application/json; charset=utf-8", 
        url: "TestRW.asmx/HelloWorld", 
        data: "{'id':" + a + "}", 
        dataType: "json", 
        success: function (response) { 
         alert(JSON.stringify(response.d)); 

        } 
       }); 
      } 

而且你的代碼可能是這樣的做這個例子(你需要允許Web服務從腳本調用第一:「[System.Web.Script.Services.ScriptService]」):

[WebMethod] 
    public object HelloWorld(int id) 
    { 
     Dictionary<string, string> dic = new Dictionary<string, string>(); 
     dic.Add("message","success"); 

     return dic; 
    } 

在這個例子中,我使用的字典,而是喲例如,你可以使用任何帶有「消息」字段的對象。

對不起,如果我missunderstood你的意思,但我真的不明白你爲什麼想要做一個「的Response.Write」的東西。

希望我已經幫助至少。 :)

10

這個工作對我來說:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public void ReturnExactValueFromWebMethod(string AuthCode) 
{ 
    string r = "return my exact response without ASP.NET added junk"; 
    HttpContext.Current.Response.BufferOutput = true; 
    HttpContext.Current.Response.Write(r); 
    HttpContext.Current.Response.Flush(); 
} 
+1

此行幫我,但對我來說我已經添加了這些行,使其工作 Response.Flush(); Response.End(); – 2015-05-11 00:46:21

+1

ResponseEnd()導致「線程正在中止」 這適用於我! HttpContext.Current.Response.Flush(); HttpContext.Current.Response.SuppressContent = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); http://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce – Evilripper 2015-07-03 13:14:20