萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Web API 強制回傳 JSON 格式三大方法完整比較與最佳實務

前言

ASP.NET Web API 預設支援內容協商,根據 `Accept` 標頭回傳 JSON 或 XML。若需**強制只回傳 JSON**,或解決字串回傳被雙引號包裹 (`"123"`)、日期格式、駝峰命名等問題,本文詳細比較三種方法並提供最佳實務封裝。

方法一:移除 XML Formatter (全域、最簡單)


// 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。

方法二:自訂 HttpResponseMessage 手動序列化 (彈性最高、解決字串問題)


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") };
}

Controller 中使用


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"
}

方法三:自訂 IContentNegotiator (精確控制協商邏輯)


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 層處理)。

方法四:.NET Core / ASP.NET Core 內建方式 (補充)


// 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` (方法二)
方法二 (手動)HttpResponseMessagehello (純文字)完美解決
方法三 (協商器)string"\"hello\""需自訂 Formatter 處理 string
ASP.NET Corestringhello (Content-Type: text/plain)內建處理,或回傳 ContentResult

最佳實務建議總覽

專案類型推薦方案關鍵點
傳統 Web API (ASP.NET 4.x)方法二 + 封裝 ToJson Helper完全控制、解決字串問題、易測試
需保留內容協商架構方法三 + 字串型別特殊處理可單元測試協商邏輯
簡單專案、不介意字串加引號方法一最省事
ASP.NET Core 新專案內建 JSON 選項 + 移除 XML Formatter現代、標準、高效能

進階:統一 API 回應包裝格式


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 { Success = false, Code = 404, Message = "Not found" }, HttpStatusCode.NotFound);
    return WebApiHelper.ToJson(new ApiResult { Success = true, Data = user });
}



總結:Web API 強制回傳 JSON,**方法二 (手動 `HttpResponseMessage` + `Json.NET` 封裝 Helper) 是最佳平衡點**:解決字串加引號、完全控制序列化設定、易於單元測試、支援統一回應包裝。方法一最簡單但有字串缺陷。方法三架構較重。新專務直接用 ASP.NET Core 內建機制。

copyright © 萬盛學電腦網 all rights reserved