简体   繁体   English

在 ASP.NET Core 3.1 中使用带有 HttpContext.Response 的新 Json 序列化器

[英]Using new Json serializer with HttpContext.Response in ASP.NET Core 3.1

When we want to serialize an object to a JSON string in ASP.NET Core's pipeline, we need to work with HttpContext.Response.Body.WriteAsync , unless I'm missing something, as there's no Result property which we can easily use to assign a JsonResult object to.当我们想在 ASP.NET Core 的管道中将对象序列化为 JSON 字符串时,我们需要使用HttpContext.Response.Body.WriteAsync ,除非我遗漏了一些东西,因为没有我们可以轻松使用的Result属性来分配一个JsonResult对象。

Unless there's a better alternative, how exactly is serialization achieved by using the above method?除非有更好的替代方案,否则使用上述方法究竟是如何实现序列化的?

Note: The options for the JSON serializer should be the same as the (default) ones being used in ASP.NET Core 3.1.注意: JSON 序列化程序的选项应与 ASP.NET Core 3.1 中使用的(默认)选项相同。

If desired (not in our case), they can be modified via the IServiceCollection.AddJsonOptions middleware.如果需要(不是在我们的例子中),它们可以通过IServiceCollection.AddJsonOptions中间件进行修改。

Example:例子:

app.Use( next =>
{
    return async context =>
    {
        if (<someFunkyConditionalExample>)
        {
            // serialize a JSON object as the response's content, returned to the end-user.
            // this should use ASP.NET Core 3.1's defaults for JSON Serialization.
        }
        else
        {
            await next(context);
        }
    };
});

First of all, you can use these extension methods to write strings directly to your response, for example:首先,您可以使用这些扩展方法将字符串直接写入您的响应中,例如:

await context.Response.WriteAsync("some text");

Make sure you have imported the correct namespace to give you access to these extensions:确保您已导入正确的命名空间,以便您可以访问这些扩展:

using Microsoft.AspNetCore.Http;

Secondly, if you want to get the JSON serialiser settings that are being used by the framework, you can extract them from the DI container:其次,如果您想获取框架正在使用的 JSON 序列化器设置,您可以从 DI 容器中提取它们:

var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

So this would make your full pipeline code look a little like this:因此,这将使您的完整管道代码看起来像这样:

app.Use(next =>
{
    return async context =>
    {
        if (<someFunkyConditionalExample>)
        {
            // Get the options
            var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

            // Serialise using the settings provided
            var json = JsonSerializer.Serialize(
                new {Foo = "bar"}, // Switch this with your object
                jsonOptions?.Value.JsonSerializerOptions);

            // Write to the response
            await context.Response.WriteAsync(json);
        }
        else
        {
            await next(context);
        }
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpContext 是 ASP.Net Core 3.1 中的 null? - HttpContext is null in ASP.Net Core 3.1? 如何在 asp.net core 3.1 中设置 nodatime json 序列化程序 - How to setup nodatime json serializer in asp.net core 3.1 ASP.NET Core 3.1 HttpContext ObjectDisposedException 或 HttpContext 变为 null - ASP.NET Core 3.1 HttpContext ObjectDisposedException or HttpContext becomes null 在 ASP.NET Core3.1 中使用包含“System.Web.HttpContext”的旧项目 - Using legacy projects containing 'System.Web.HttpContext' in ASP.NET Core3.1 ASP.NET 核心 3.1 HttpContext.Connection.ClientCertificate 还是 HttpContext.Connection.GetClientCertificateAsync? - ASP.NET Core 3.1 HttpContext.Connection.ClientCertificate or HttpContext.Connection.GetClientCertificateAsync? asp.net core 3.1 上的 Json 请求 - Json request on asp.net core 3.1 带有自定义响应包装器的 ASP.NET Core 3.1 Web API 中的 JSON 响应中断 - JSON response breaks in ASP.NET Core 3.1 Web API with custom response wrapper Asp.Net Core 2 中是否有等同于“HttpContext.Response.Write”的东西? - Is there an equivalent to "HttpContext.Response.Write" in Asp.Net Core 2? ASP.NET Core中的HttpContext RESPONSE END如何 - How HttpContext RESPONSE END in ASP.NET Core 在 C# 中只返回来自 json HttpContext.Response 的键 - Return just Keys from json HttpContext.Response in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM