2014-09-12 59 views
-1

我是新來ASP.net(Visual Studio 2010中,.NET 3.5),我想做到以下幾點:包裝所有ASP.net JSON響應/返回一個匿名對象

我使用OperationContracts到將Web服務數據提供爲JSON。用angularJS編寫的移動應用程序正在使用這些JSON響應。

我希望每個OperationContract響應都是由標準響應對象包裝的相關數據對象。

e.g:

{ 
    error: false, 
    error_detail: '', 
    authenticated: false, 
    data: { } 
} 

內的數據變量將任何需要每個單獨的請求類型的。

移動應用程序檢查相關變量,如果一切正常,則將數據傳遞給任何請求的數據(此部分正在工作並準備就緒)。

我知道它經常被人忽視,但我希望基本上可以返回一個匿名對象,因爲我可以很容易地構建一個匿名對象和任何我需要的數據,但似乎我強烈否認這樣做的能力。理想情況下,我不想在移動應用程序端添加另一層反序列化或其他內容,我希望儘可能少地處理客戶端。

我很容易就能根據自己的測試Web API項目(請參閱下面的示例控制器)獲得此項工作,但不幸的是我正在添加到現有項目中,而不是開始新項目。

任何人都可以提供任何建議嗎?

示例Web API代碼

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 

namespace tut3.Controllers 
{ 
    public class ValuesController : ApiController 
    { 

     /** 
     * Take the provided dataResponse object and embed it into 
     * the data variable of the default response object 
     **/ 
     private object Response(object dataResponse) 
     { 
      return new 
      { 
       success = false, 
       error = "", 
       error_detail = "", 
       authenticated = false, 
       token = "", 
       token_expiry = 0, 
       data = dataResponse 
      }; 
     } 


     /** 
     * This could be a normal web service that uses the Knadel database etc etc, the only difference is 
     * the return is sent through the Response() function 
     **/ 
     public object Get() 
     { 

      object[] local = new[] { 
       new { cat = "cat", dog = "dog" }, 
       new { cat = "cat", dog = "dog" }, 
       new { cat = "cat", dog = "dog" }, 
       new { cat = "cat", dog = "dog" }, 
       new { cat = "cat", dog = "dog" } 
      }; 

      /** 
      * Pass local to Response(), embed it in data and then return the whole thing 
      **/ 
      return Response(local); 

     } 

    } 
} 

回答

1

由於您使用在客戶端上AngularJS,因此直接食用的JSON響應不存在反序列化(或任何類似的是)在客戶端上。您正在向客戶端傳遞一個可直接由AngularJS(或任何其他JS客戶端)使用的「javascript對象」。

與匿名對象相比,使用類型化對象(使用簡單成員變量!)在服務器上沒有序列化懲罰。 我個人更喜歡任何一天打字對象。

至於返回對象的結構,使用異常將會更容易和更清晰,並且允許承諾鏈中的失敗回調負責錯誤處理。 也就是說如果你拋出一個異常,服務器端會通過像這樣被抓:

$http.get('yourServerUrl').then(function successCallback(result){ 
     // Everything went well, display the data or whatever 
     }, function errorCallback(error){ 
     // Something went wrong, 
     // the error object will contain statusCode and the message from the exception 
    }); 

令牌,認證信息等應該去的HTTP頭中,而不是在響應主體。

HTH,

卡斯帕

+0

感謝卡斯帕爾,遺憾或不響應更快。我曾希望能避免嚴格定義被髮回的對象,但我認爲情況並非如此,實際上這並不是什麼大事。 – 2015-03-05 11:41:13