使用JSON.NET返回ActionResult

这个问题在这里已经有了答案:

  • Json.Net和ActionResult 2的答案

  • 我发现了一个类似的stackoverflow问题:Json.Net和ActionResult

    那里的答案建议使用

    return Content( converted, "application/json" );
    

    这似乎在我非常简单的页面上工作。


    而不是使用JSON.NET进行序列化,然后调用Json() ,而不是重写控制器中的Json()方法(或者可能是基本控制器以增强其可重用性)?

    这是从这篇博文中拉出来的。

    在您的控制器(或基本控制器)中:

    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior
        };
    }
    

    JsonNetResult的定义如下:

    public class JsonNetResult : JsonResult
    {
        public JsonNetResult()
        {
            Settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            };
        }
    
        public JsonSerializerSettings Settings { get; private set; }
    
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");
    
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
    
            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;
            if (this.Data == null)
                return;
    
            var scriptSerializer = JsonSerializer.Create(this.Settings);
    
            using (var sw = new StringWriter())
            {
                scriptSerializer.Serialize(sw, this.Data);
                response.Write(sw.ToString());
            }
        }
    }
    

    通过这样做,当您在控制器中调用Json()时,您将自动获得所需的JSON.NET序列化。

    链接地址: http://www.djcxy.com/p/48135.html

    上一篇: Using JSON.NET to return ActionResult

    下一篇: knockout dates being reset on post to mvc controller