簡體   English   中英

.net 核心 web api - Z594C103F2C6E04C3D8AB059F031E0 可以傳遞參數到中間件嗎?

[英].net core web api - Can controller pass parameters to middleware?

嗨,我需要捕獲 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,您可以在中間件中配置您的響應。

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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM