﻿# ASP.NET Web API 如何透過程式決定回應XML或JSON格式

雖然 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式，並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式，不過有時候我們的確也需要讓程式來控制要回應哪種格式，本文將介紹如何讓 ASP.NET Web API 自訂回應結果格式 (XML 或 JSON)，以方便透過其他方法來決定如何回應訊息格式。

我們先來看看 ASP.NET MVC 4 專案範本幫我們產生預設 API 裡的 Get() 方法，程式碼非常簡單：

```csharp
// GET api/values
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}
```

如果我們要自訂回應格式的話，那麼 API 的回傳型別必須改成 [HttpResponseMessage](http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage.aspx) 才行，並透過以下程式碼做到自訂切換回應格式的動作：

```csharp
// GET api/values
public HttpResponseMessage Get(string output = null)
{
    var data = new string[] { "value1", "value2" };

    var resp = new HttpResponseMessage(HttpStatusCode.OK);

    if (output == "xml")
    {
        resp.Content = new ObjectContent<IEnumerable<string>>(data, new XmlMediaTypeFormatter());
    }
    else
    {
        resp.Content = new ObjectContent<IEnumerable<string>>(data, new JsonMediaTypeFormatter());
    }

    return resp;
}
```

這段程式碼我大概解釋一下：

-   第 2 行：透過 ASP.NET MVC 的模型繫結機制取得 Query String 上的 output 參數
-   第 6 行：建立 HttpResponseMessage 物件，並指定 HTTP 回傳狀態為 200 (OK)
-   第 8 ~ 15 行：自訂回應內容的程式碼，我們要透過 [ObjectContent](http://msdn.microsoft.com/en-us/library/system.net.http.objectcontent\(VS.108\).aspx) 型別傳入一個泛型參數來建立內容物件，而這個泛型參數就是在修改之前 Get() 方法的回傳型別 IEnumerable<string\>，傳入的第一個參數是要輸出的資料，第二個參數則是輸出格式，這時你就可以選擇輸出 [XmlMediaTypeFormatter](http://msdn.microsoft.com/en-us/library/system.net.http.formatting.xmlmediatypeformatter\(VS.108\).aspx) 還是 [JsonMediaTypeFormatter](http://msdn.microsoft.com/en-us/library/system.net.http.formatting.jsonmediatypeformatter\(VS.108\).aspx) 了。

如果要對該 API 進行測試，可以輸入以下網址路徑：

-   **/api/values?output=xml**
-   **/api/values?output=json**

**相關連結**

-   [An Introduction to ASP.NET Web API](https://weblog.west-wind.com/posts/2012/Aug/21/An-Introduction-to-ASPNET-Web-API)
-   [Source code for ASP.NET WebApi Article for Code Magazine](https://github.com/RickStrahl/AspNetWebApiArticle)
-   [Web API : The Official Microsoft ASP.NET Site](http://www.asp.net/web-api)
