Returning unescaped Json in MVC with Json.Net

前端 未结 4 925
情深已故
情深已故 2020-12-29 06:17

How does one return unescaped Json, using Json.Net in an MVC project?

So far, I serialize a basic object, and get Json.Net to serialize it:

public Js         


        
4条回答
  •  清歌不尽
    2020-12-29 06:41

    The object is already serialized by Json.NET, and when you pass it to Json() it gets encoded twice. If you must use Json.NET instead of the built in encoder, then the ideal way to handle this would be to create a custom ActionResult accepts the object and calls Json.net internally to serialize the object and return it as an application/json result.

    EDIT

    This code is for the solution mentioned above. It's untested, but should work.

    public class JsonDotNetResult : ActionResult
    {
        private object _obj { get; set; }
        public JsonDotNetResult(object obj)
        {
            _obj = obj;
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.AddHeader("content-type", "application/json");
            context.HttpContext.Response.Write(JsonConvert.SerializeObject(_obj));
        }
    }
    

    and in your controller just do:

    return new JsonDotNetResult(result);
    

提交回复
热议问题