简体   繁体   中英

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

Hi I need to catch exceptions for http requests, eg:

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

now since there are many http requests, I want to use a middleware to globally handle exceptions rather than
writing try-catch statement in each http request as above.

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"?
        }
    }
}

I do not know how to assign Errorcode using the middleware approach as I comment out above. Is it possible? Thanks.

If I understand your requirements well I suggest this:

You don't need access TestResponse and you can configure your response in middleware.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM