Search code examples
.netasp.net-core.net-coremiddleware

Authorize Middleware not block the request


To validate my API access for the selected users i had write the Middleware for the validate user http request Middleware is executing and alter the StatusCode of request

but still API method is executing

here is my middleware

 httpContext.Response.StatusCode = 401;
 httpContext.Response.WriteAsync("Invalid username or password.");

return _next(httpContext);

here im register the Middleware

app.UseAuthenticationMiddleware();

here is my API method

[HttpPost]       
public async Task<IActionResult> CreatePolicy([FromBody] Customer customerDetails)

here i also add the [Authorize] add its not working return the 500 error

any suggestions ?


Solution

  • When writing a custom middleware, you have to call await _next(httpContext) to execute the next middleware in the pipeline.

    Remove it (conditionally) and it won't called the middlewares further in the pipeline.

    if(someConditionIsTrue)
    {
        await _next(httpContext);
    }
    

    Alternatively you can just return a completed task via return Task.Completed; instead of return _next(httpContext), if don't want to call other middlewares in the pipeline.

    But its a micro optimization, since the 2nd one doesn't invoke an async state machine.