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