ASP.NET Web API 預設支援內容協商,根據 `Accept` 標頭回傳 JSON 或 XML。若需**強制只回傳 JSON**,或解決字串回傳被雙引號包裹 (`"123"`)、日期格式、駝峰命名等問題,本文詳細比較三種方法並提供最佳實務封裝。
// WebApiConfig.cs 或 Global.asax Application_Start
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// ... 路由設定 ...
// 移除 XML Formatter,只保留 JSON
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
// 進階:設定 JSON 格式化選項
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
json.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
優點:一行程式碼全域生效。
缺點:**字串型別回傳會被序列化為 JSON 字串 (含雙引號)**,如 `return "ok"` → `"\"ok\""`。無法針對單一 Action 例外輸出 XML。
public HttpResponseMessage GetStringData()
{
string rawString = "純文字內容";
// 手動建立 JSON 回應,字串不被加引號
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(rawString, Encoding.UTF8, "application/json")
};
return response;
}
public HttpResponseMessage GetObjectData()
{
var data = new { Id = 1, Name = "Test", Time = DateTime.Now };
// 使用 Json.NET 序列化
string json = JsonConvert.SerializeObject(data, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateFormatString = "yyyy-MM-dd HH:mm:ss"
});
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
}
public static class WebApiHelper
{
private static readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateFormatString = "yyyy-MM-dd HH:mm:ss",
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
public static HttpResponseMessage ToJson(object obj, HttpStatusCode status = HttpStatusCode.OK)
{
string content;
if (obj is string || obj is char) // 字串/字元直接輸出,不序列化
content = obj.ToString();
else
content = JsonConvert.SerializeObject(obj, _jsonSettings);
return new HttpResponseMessage(status)
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
}
public static HttpResponseMessage ToJson(object obj, string customJson, HttpStatusCode status = HttpStatusCode.OK)
=> new HttpResponseMessage(status) { Content = new StringContent(customJson, Encoding.UTF8, "application/json") };
}
public HttpResponseMessage GetUser(int id)
{
var user = _service.GetUser(id);
if (user == null) return WebApiHelper.ToJson(new { error = "Not found" }, HttpStatusCode.NotFound);
return WebApiHelper.ToJson(user);
}
public HttpResponseMessage GetStatus()
{
return WebApiHelper.ToJson("running"); // 直接輸出 running,非 "running"
}
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
public class JsonOnlyNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonOnlyNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable formatters)
{
// 無視 Accept 標頭,永遠回傳 JSON
return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
}
}
// 註冊 (WebApiConfig.cs)
public static void Register(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// ... 其他設定
config.Services.Replace(typeof(IContentNegotiator), new JsonOnlyNegotiator(jsonFormatter));
}
優點:保留內容協商架構、可針對特定型別邏輯、單元測試友善。
缺點:同樣面臨字串型別被加引號問題 (需在 Formatter 層處理)。
// Startup.cs
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
})
.AddXmlSerializerFormatters(); // 若需 XML 顯式加入,預設不加
// 或移除 XML (較新版本)
services.AddControllers(options =>
{
options.OutputFormatters.RemoveType();
options.OutputFormatters.RemoveType();
});
問題:`return "hello"` → 客戶端收到 `"\"hello\""` (JSON 字串字面值)。
| 方法 | 回傳型別 | 結果 | 解決 |
|---|---|---|---|
| 方法一 (移除 XML) | string | "\"hello\"" | 改回傳 `HttpResponseMessage` (方法二) |
| 方法二 (手動) | HttpResponseMessage | hello (純文字) | 完美解決 |
| 方法三 (協商器) | string | "\"hello\"" | 需自訂 Formatter 處理 string |
| ASP.NET Core | string | hello (Content-Type: text/plain) | 內建處理,或回傳 ContentResult |
| 專案類型 | 推薦方案 | 關鍵點 |
|---|---|---|
| 傳統 Web API (ASP.NET 4.x) | 方法二 + 封裝 ToJson Helper | 完全控制、解決字串問題、易測試 |
| 需保留內容協商架構 | 方法三 + 字串型別特殊處理 | 可單元測試協商邏輯 |
| 簡單專案、不介意字串加引號 | 方法一 | 最省事 |
| ASP.NET Core 新專案 | 內建 JSON 選項 + 移除 XML Formatter | 現代、標準、高效能 |
public class ApiResult
{
public bool Success { get; set; }
public T Data { get; set; }
public string Message { get; set; }
public int Code { get; set; }
}
// Action 統一回傳
public HttpResponseMessage GetUser(int id)
{
var user = _service.GetUser(id);
if (user == null) return WebApiHelper.ToJson(new ApiResult
總結:Web API 強制回傳 JSON,**方法二 (手動 `HttpResponseMessage` + `Json.NET` 封裝 Helper) 是最佳平衡點**:解決字串加引號、完全控制序列化設定、易於單元測試、支援統一回應包裝。方法一最簡單但有字串缺陷。方法三架構較重。新專務直接用 ASP.NET Core 內建機制。