Asp.net-Mvc-3

使用 JSON.NET 作為 ASP.NET MVC 3 中的預設 JSON 序列化程序 - 可能嗎?

  • August 18, 2011

是否可以在 ASP.NET MVC 3 中使用JSON.NET作為預設 JSON 序列化程序?

根據我的研究,似乎實現這一點的唯一方法是將 ActionResult 擴展MVC3 中的 JsonResult 不是虛擬的……

我希望通過 ASP.NET MVC 3 可以指定一個可插入的提供程序以序列化為 JSON。

想法?

我相信最好的方法是 - 如您的連結中所述 - 直接擴展 ActionResult 或擴展 JsonResult 。

至於控制器上非虛的方法JsonResult 不成立,選擇合適的重載即可。這很好用:

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)

編輯 1:一個 JsonResult 擴展…

public class JsonNetResult : JsonResult
{
   public override void ExecuteResult(ControllerContext context)
   {
       if (context == null)
           throw new ArgumentNullException("context");

       var response = context.HttpContext.Response;

       response.ContentType = !String.IsNullOrEmpty(ContentType) 
           ? ContentType 
           : "application/json";

       if (ContentEncoding != null)
           response.ContentEncoding = ContentEncoding;

       // If you need special handling, you can call another form of SerializeObject below
       var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
       response.Write(serializedObject);
   }

編輯 2:根據以下建議,我刪除了對 Data 為 null 的檢查。這應該使 JQuery 的較新版本感到高興,並且似乎是明智的做法,因為響應可以被無條件地反序列化。但請注意,這不是來自 ASP.NET MVC 的 JSON 響應的預設行為,而是在沒有數據時以空字元串響應。

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