Asp.net-Mvc-4

MVC 4 - Web Api 和 JSON?

  • February 17, 2015

我正在加強 MVC 4 的 Web API,我對預設格式有點困惑。我希望 API 數據採用 JSON 格式。但是,它以 XML 形式返回它。根據http://www.asp.net/web-api/videos/getting-started/your-first-web-api上的 MVC 4 入門影片,預設情況下應該是 JSON。但是當我創建一個新的 Web Api 項目並執行範例時,我得到了這個:

<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>

我一直在兜圈子,試圖在 JSON 中得到這個,但顯然有很多關於這個的錯誤資訊。如:

  1. 如果我將“application/json”添加到內容類型標頭,它應該返回 JSON。這不起作用,但我懷疑我沒有正確的標題變數名稱,因為我沒有找到要使用的確切名稱。我在請求標頭中嘗試了“Content-Type”和“contentType”,但沒有成功。此外,我預設需要 JSON,而不是根據標題資訊。
  2. 如果我創建一個 JsonFormatter 並將其添加到 Application_StartGlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings));它應該可以解決問題。但是我收集了這個貶值的例子,因為沒有一個例子有效。

我可以做什麼,最好是簡單的,預設以 JSON 格式輸出數據?

將此添加到 GLOBAL.ASAX 以獲取application/json的響應

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

所以它在上下文中應該是這樣的:

protected void Application_Start()
{
   AreaRegistration.RegisterAllAreas();

   RegisterGlobalFilters(GlobalFilters.Filters);
   RegisterRoutes(RouteTable.Routes);

   BundleTable.Bundles.RegisterTemplateBundles();
   GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

或者,如果您需要將 XML 保留為媒體類型,則可以改為編輯App_Start/WebApiConfig.cs

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );

這使得 JSON 成為 Web 瀏覽器的預設響應,但返回text/html

資源

引用自:https://stackoverflow.com/questions/12904972