【发布时间】:2020-06-27 15:37:35
【问题描述】:
当我们想在 ASP.NET Core 的管道中将对象序列化为 JSON 字符串时,我们需要使用 HttpContext.Response.Body.WriteAsync,除非我遗漏了什么,因为没有我们可以轻松使用的 Result 属性分配一个JsonResult 对象。
除非有更好的替代方案,否则使用上述方法究竟是如何实现序列化的?
注意: JSON 序列化程序的选项应与 ASP.NET Core 3.1 中使用的(默认)选项相同。
如果需要(不是我们的例子),可以通过IServiceCollection.AddJsonOptions 中间件修改它们。
例子:
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);
}
};
});
【问题讨论】:
-
我相信原生 JSON 支持是通过 System.Text.Json 添加的。您是否尝试过使用它? devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis
-
您可以这样发送对象,以便 .net 运行时本身将其序列化为 json 并将响应作为 json 发送给调用者。类似于下面的那个。
// GET api/authors/RickAndMSFT [HttpGet("{alias}")] public Author Get(string alias) { return _authors.GetByAlias(alias); } -
我对你的问题感到困惑。你到底想做什么?你只是想连载吗?所以像
var json = System.Text.Json.JsonSerializer.Serialize(new {x = 5})? -
-
有一个扩展方法可以直接处理字符串docs.microsoft.com/en-us/dotnet/api/…
标签: c# json asp.net-core httpcontext asp.net-core-middleware