[英]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.