学无先后,达者为师

网站首页 编程语言 正文

aspnet core中间件 短路 Response.WriteAsync正确用法

作者:ChasingCode 更新时间: 2022-09-25 编程语言

在stack overflow上回答了一个问题,随便在这记录下。

在aspnetcore3.1的中间件,在短路时,如果需要自定响应的内容和code,需要注意的问题。

使用 Response.WriteAsync()和Response.StatusCode 定义的body和code时,如果不按套路出牌就会导致body不显示,正确的用法是,

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
   //Unauthorized
   context.Response.Headers.Add("Content-Type", "application/json");
   context.Response.StatusCode = StatusCodes.Status401Unauthorized;
   await context.Response.WriteAsync(JsonConvert.SerializeObject(new
   {
       Msg = msg,
       LoginPath = _options.LoginPath.Value,
   }));
   await context.Response.CompleteAsync();
}

见图(懒得打字了)

如果对你有用请点赞

 

原文链接:https://blog.csdn.net/m0_62367247/article/details/126812968

栏目分类
最近更新