首页 > 解决方案 > 关闭异步响应

问题描述

我正在尝试关闭当前响应,但是当我尝试HttpContext.Response.Body.Close()并且Response.End()不存在时没有任何反应。

我试图实现这一点的原因是由于遗留验证器函数会写入错误并关闭响应,或者至少停止父 WebAPI 方法。

例子:

    private async Task Register_v2()
    {
        //Read JSON to object
        UserRegisterRequest userRegisterRequest = Request.ReadBody().FromJson<UserRegisterRequest>();

        //Validate object (legacy static method with a lot of logic)
        //Validate() should end the response if object not validated
        userRegisterRequest.Validate(isJson: true, isThrowHttpError: true);

        //Code still reaches here and request does not close
        string test = "hey I'm alive";
   } 

我可以以某种方式使用中间件解决这个问题吗?

谢谢

标签: asp.net-core-mvcasp.net-core-2.0

解决方案


There are two ways to terminate the Request pipeline.

  • Use app.Run in Startup.Configure
  • Do not invoke _next(context) in Middleware.InvokeAsync

For your scenario, you could try second option by determining whether to invoke _next(context).

public class FirstMiddleware
{
    private readonly RequestDelegate _next;
    public FirstMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        await context.Response.WriteAsync($"This is { GetType().Name }");
        //decide whether to invoke line below based on your business logic
        //await _next(context);
        bool isValid = userRegisterRequest.Validate(isJson: true, isThrowHttpError: true); 
      //change userRegisterRequest.Validate to reutrn whether the model is valid
       if(!isValid)
       {
             await context.Response.WriteAsync($"Model is not valid");
       }
       else
       {
             await _next(context);
        }
    }
}

推荐阅读