【问题标题】:Will JsonContent get serialised multiple times using Json.NET in Web Api 2JsonContent 是否会在 Web Api 2 中使用 Json.NET 多次序列化
【发布时间】:2015-02-11 13:52:33
【问题描述】:

如果我有这个控制器:

public class SomeController : ApiController
{
    public SomeInfoDto Get()
    {
        return new SomeInfoDto();
    }
}

当我使用 get 请求调用 /api/Some 时,我会在 Content Body 中获得 JSON,因为 JSON.NET 已经为我提供了序列化它。

但是,如果我想发送一个 500 HTTP 代码和一些 JSON 我想我可以这样做:

public HttpResponseMessage Get()
{
    return new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
        Content = // not sure what to put here
    }
}

所以我用谷歌搜索了Content 的内容并找到了这个resource

public class JsonContent : HttpContent
{
    private readonly JToken _value;

    public JsonContent(JToken value)
    {
        _value = value;
        Headers.ContentType = new MediaTypeHeaderValue("application/json");
    }

    protected override Task SerializeToStreamAsync(Stream stream,
        TransportContext context)
    {
        var jw = new JsonTextWriter(new StreamWriter(stream))
        {
            Formatting = Formatting.Indented
        };
        _value.WriteTo(jw);
        jw.Flush();
        return Task.FromResult<object>(null);
    }

    protected override bool TryComputeLength(out long length)
    {
        length = -1;
        return false;
    }
}

我可以轻松修改以适合我的目的。

但是,我的问题是,如果我让 SerializeToStreamAsync 在 Web Api 管道的下游使用 JsonConvert.SerializeObject(_value),它会再次被序列化吗?

我已经这样设置了GlobalConfiguration.Configuration

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

我对@9​​87654334@ 的实现是这样的:

protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
    using (var streamWriter = new StreamWriter(stream))
    {
        streamWriter.WriteAsync(JsonConvert.SerializeObject(this.value)).Wait();
        streamWriter.FlushAsync().Wait();
    }

    return Task.FromResult<object>(null);
}

【问题讨论】:

    标签: asp.net json asp.net-web-api asp.net-web-api2


    【解决方案1】:

    编辑:提供带有格式化程序的具体示例。 如果要发送带有 Http Status Code 500 的 JSON 内容,可以使用扩展方法 HttpRequestMessage.CreateResponse。不需要任何高级序列化和格式化。更多信息请点击此处。

    https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.createresponse%28v=vs.118%29.aspx

    Request.CreateResponse(HttpStatusCode.InternalServerError, new string[] { "value1", "value2" }, new JsonMediaTypeFormatter())
    

    (或)

    Request.CreateResponse(HttpStatusCode.InternalServerError, new string[] { "value1", "value2" }, 'application/json')
    

    【讨论】:

    • 我在一个新鲜的 Web Api 项目中使用了它,并且输出被序列化为 xml,我猜你必须将 MediaFormatter 设置为 JSON 对吗?
    • 如果您可以将此示例添加到您的答案中,我会接受,只是为了回答完整性:Request.CreateResponse(HttpStatusCode.InternalServerError, new string[] { "value1", "value2" }, new JsonMediaTypeFormatter())
    • 如果你想要全局配置的,你可以使用GlobalConfiguration.Configuration.Formatters.JsonFormatter而不是new JsonMediaTypeFormatter()
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2014-01-29
    • 2013-12-21
    • 2023-03-08
    相关资源
    最近更新 更多