萬盛學電腦網

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

ASP.NET Web Service (ASMX) 回傳 JSON 完整實作:JavaScriptSerializer、Json.NET 與前端呼叫

前言

傳統 ASP.NET Web Service (`.asmx`) 預設回傳 XML。若需回傳 JSON 供前端 AJAX 呼叫,需手動序列化並設定 `Response.ContentType`。本文提供三種實作方式:`JavaScriptSerializer` (內建)、`Json.NET` (推薦)、`ScriptMethod` 屬性簡化輸出,並說明前端 jQuery 呼叫細節。

方式一:手動序列化 + Response.End() (最通用、完全控制)


[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] // 允許腳本調用 (啟用 JSON 回傳)
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    public void GetUserInfo(string userId)
    {
        // 1. 業務邏輯取得資料
        var user = UserService.GetById(userId);
        if (user == null)
        {
            ReturnError("用戶不存在");
            return;
        }

        // 2. 序列化為 JSON (使用 Json.NET 推薦)
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(user, new Newtonsoft.Json.JsonSerializerSettings
        {
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), // 駝峰命名
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
        });

        // 3. 輸出 JSON
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(json);
        HttpContext.Current.Response.End(); // 關鍵:結束回應,避免輸出 XML 宣告
    }

    private void ReturnError(string message)
    {
        var error = new { success = false, message };
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(error);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(json);
        HttpContext.Current.Response.End();
    }
}

方式二:使用 ScriptMethod 屬性自動 JSON 序列化 (簡潔但靈活度較低)


[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] // 強制 JSON、POST
    public UserInfo GetUserInfo(string userId)
    {
        // 直接回傳物件,ASP.NET AJAX 自動序列化為 JSON
        return UserService.GetById(userId) ?? throw new Exception("用戶不存在");
    }
    
    // 複雜型別回傳
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public PagedResult SearchUsers(string keyword, int page, int pageSize)
    {
        return UserService.Search(keyword, page, pageSize);
    }
}

注意:`ScriptMethod` 使用內建 `JavaScriptSerializer`,序列化效能較差、不支援駝峰命名、日期格式固定為 `/Date(1234567890)/`、循環參考會拋出異常。複雜場景建議用方式一。

方式三:Generic Handler (.ashx) 替代 ASMX (更輕量、REST 風格)


<%@ WebHandler Language="C#" Class="UserHandler" %>
using System.Web;
using Newtonsoft.Json;

public class UserHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json; charset=utf-8";
        string action = context.Request.QueryString["action"] ?? "list";
        
        try
        {
            object result;
            switch (action)
            {
                case "get":
                    string id = context.Request.QueryString["id"];
                    result = UserService.GetById(id);
                    break;
                case "list":
                    int page = int.Parse(context.Request.QueryString["page"] ?? "1");
                    int size = int.Parse(context.Request.QueryString["size"] ?? "20");
                    result = UserService.GetPaged(page, size);
                    break;
                default:
                    throw new ArgumentException("未知 action");
            }
            
            string json = JsonConvert.SerializeObject(new { success = true, data = result }, 
                new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            context.Response.Write(json);
        }
        catch (Exception ex)
        {
            string json = JsonConvert.SerializeObject(new { success = false, message = ex.Message });
            context.Response.Write(json);
        }
    }
    public bool IsReusable => false;
}

前端 jQuery AJAX 呼叫範例



關鍵細節總結

項目手動 Response.Write (方式一)ScriptMethod (方式二)ASHX (方式三)
序列化器自訂 (Json.NET 推薦)JavaScriptSerializer (內建)自訂 (Json.NET 推薦)
日期格式可控 (yyyy-MM-dd)固定 /Date(ms)/可控
命名慣例可控 (CamelCase)PascalCase (屬性名)可控
循環參考可設定忽略拋出異常可設定忽略
錯誤處理完全自訂自動包裝 SOAP Fault完全自訂
測試便利性瀏覽器直接開啟 .asmx?op=... 會顯示 XML 測試頁同左瀏覽器直接開啟 .ashx 顯示 JSON

常見問題解決

Q: 回傳 XML 而非 JSON?
1. 確認 `[ScriptService]` 屬性已加在類別上。
2. 確認 `contentType: 'application/json'` 在 AJAX 設定中。
3. 方式一:確認 `Response.ContentType = "application/json"` 且 `Response.End()`。
4. 方式二:確認 `[ScriptMethod(ResponseFormat = ResponseFormat.Json)]`。
Q: 日期顯示為 /Date(1234567890)/?
內建 `JavaScriptSerializer` 固定格式。解決:改用方式一/三 + Json.NET 設定 `DateFormatString`,或前端格式化 `new Date(parseInt(jsonDate.substr(6)))`.
Q: 循環參考錯誤?
實體間雙向導航屬性。解決:Json.NET 設定 `ReferenceLoopHandling.Ignore` 或使用 DTO 斷開循環。
Q: GET 請求被拒絕?
ASMX 預設封鎖 GET 以防 CSRF。需加 `[ScriptMethod(UseHttpGet = true)]` 並確認安全性。

總結:ASMX 回傳 JSON **推薦方式一 (手動 Json.NET + Response.End)**,擁有完全序列化控制權、最佳效能、標準日期/命名格式。簡單場景可用方式二 `ScriptMethod`。新專案建議直接用 **ASP.NET Core Web API** 或 **ASHX** 替代 ASMX,架構更現代、輕量、易測試。

copyright © 萬盛學電腦網 all rights reserved