从ASP返回JavaScript对象文字,而不是JSON字符串.. NET MVC端点



由于各种原因,我已经从ASP。. NET MVC的内置JSON序列化器(返回一个System.Web.Mvc.JsonResult对象(见下面的编辑))到Newtonsoft。直到开始测试后我才意识到前者返回一个JavaScript对象文字,而Newtonsoft返回一个JSON格式的字符串

我不喜欢在客户端解析JSON字符串——把它作为对象文字是非常方便的——但是出于其他技术原因,我想坚持使用Newtonsoft。

例如,不是在我的客户端看到这个结果…

"{"Errors":["Please enter a valid email address."],"HasErrors":true}"

…我想看到这样的结果:

{"Errors":["Please enter a valid email address."],"HasErrors":true} // no quotes

是否有办法使Newtonsoft返回JS对象字面值而不是字符串?

<标题>编辑

我提出问题的方式不是最好的。JsonResult型没有任何问题。实际上,解决方案仍然使用它。唯一的问题是默认的Controller.Json方法,它可以被重写以使用Newtonsoft (Json.NET)代替内置的序列化器。

编写一个使用Newtonsoft序列化器的自定义JsonResult:

类似以下内容:

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

JsonNetResult.cs:

using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
public class JsonNetResult : JsonResult
{   
    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }
    public JsonNetResult()
    {
        Formatting = Formatting.None;
        SerializerSettings = new JsonSerializerSettings();
        JsonRequestBehavior = JsonRequestBehavior.DenyGet;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet
            && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
        }
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = !string.IsNullOrEmpty(ContentType)
                                    ? ContentType
                                    : "application/json";
        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;
        if (Data != null)
        {
            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
            var serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);
            writer.Flush();
        }
    }
}

信用:https://gist.github.com/jpoehls/1424538

答案就在这里:如何强迫ASP. NET Web API总是返回JSON?

摘录:

清除所有格式化器并重新添加Json格式化器

GlobalConfiguration.Configuration.Formatters.Clear ();GlobalConfiguration.Configuration.Formatters。添加(新JsonMediaTypeFormatter ());编辑

我把它添加到全局。

相关内容

  • 没有找到相关文章

最新更新