【问题标题】:.net core web api - Can controller pass parameters to middleware?.net core web api - 控制器可以将参数传递给中间件吗?
【发布时间】:2020-10-27 23:00:23
【问题描述】:

您好,我需要捕获 http 请求的异常,例如:

    [HttpPost("Test")]
    public async Task<ActionResult<TestResponse>> Test(TestRequest request)
    {
        TestResponse result;
        try
        {
           // call 3rd party service
        }
        catch(exception ex)
        {
          result.Errorcode = "Mock" // This Errorcode will be used by client side
        }

        return Ok(result);
    }

现在由于有很多http请求,我想使用中间件来全局处理异常而不是
如上所述在每个 http 请求中编写 try-catch 语句。

public class Middleware
{
    readonly RequestDelegate next;

    public Middleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await next(httpContext);
        }
        catch (Exception ex)
        {
            // is there a way to pass TestResponse here so I can do  result.Errorcode = "Mock"?
        }
    }
}

正如我在上面注释的那样,我不知道如何使用中间件方法分配错误代码。可能吗?谢谢。

【问题讨论】:

  • TestResponse 是您的响应模型吗?我的意思是它是你所有 api 的响应结构吗?
  • @Arsalan Valoojerdi 我有一个名为 BaseResponse 的抽象类,它定义了属性“ErrorCode”,从 BaseResponse 继承了多个类用于不同的 api,例如 TestResponse。
  • 您可以使用自定义异常并在中间件中捕获它,但您需要在控制器操作的 catch 块中重新抛出。或者将值存储在 HttpContext (this.HttpContext.Items["my-key"] = "my values";)
  • 发生异常后是否还有其他数据要发送给客户,或者只是错误代码?
  • @Arsalan Valoojerdi 只有 2 个属性 - 来自 ResponseModel 的错误代码和错误详细信息

标签: c# asp.net-web-api error-handling middleware


【解决方案1】:

如果我能很好地理解您的要求,我建议这样做:

您不需要访问 TestResponse,您可以在中间件中配置您的响应。

public class FailResponseModel
{
    public FailResponseModel(string errorCode, object errorDetails)
    {
        ErrorCode = errorCode;
        ErrorDetails = errorDetails;
    }

    public string ErrorCode { get; set; }

    public object ErrorDetails { get; set; }
}

public class ExceptionHandlerMiddleware
{
    readonly RequestDelegate next;

    public Middleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await next(httpContext);
        }
        catch (Exception ex)
        {
            httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            httpContext.Response.ContentType = "application/json";
            var response =
                JsonConvert.SerializeObject(new FailResponseModel("your-error-code", "your-error-details"));

            await httpContext.Response.WriteAsync(response);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2017-08-04
    • 2013-01-09
    相关资源
    最近更新 更多