簡體   English   中英

HttpResponseMessage的內容為JSON

[英]Content of HttpResponseMessage as JSON

我有一個ASP.NET MVC WEB API。 由於幾個原因(由於沒有授權重定向..),我不能只使用一個簡單的對象並在我的控制器方法中返回它。 因此我需要HttpResponseMessage類,它允許我重定向。

目前我這樣做:

var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
var formatter = new JsonMediaTypeFormatter();
response.Content = new ObjectContent<Response>(response, formatter, "application/json");

..將序列化為JSON的對象放入HttpResponseMessage的內容中。 不知何故,我覺得還有另一種更好的方法。 有什么想法嗎?

你可以做:

var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
Request.CreateResponse<Response>(HttpStatusCode.OK, response);

默認情況下,Web API將根據HTTP請求標頭中指定的Content-Type設置響應的格式,但CreateResponse方法中存在一些重載,您可以在其中指定類型格式化程序。

您還可以刪除Web API XML序列化程序以強制所有響應為JSON(如果這是您想要的) - 我認為它是HttpConfiguration上的Formatters.Remove方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM