I have custom authentication and authorization handlers, but there is still a custom middleware to check few other things on another scenario. Here is some code for exception handler
app.UseExceptionHandler("/Error/{0}");
app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/Error/{0}");
The custom middleware code is below. This is a test code. I want to come out of the middleware on some conditions. The below code does not work (it won't go to error controller). When I use response.Redirect(), it works, but then it goes on infinite redirects. I've thought of return Forbid(), return StatusCodeResult(403), but the return type is Task.
public async Task Invoke(HttpContext context)
{
context.Response.StatusCode = 403;
await _next(context);
return;
CodePudding user response:
I tried the following and it worked. I think the complete call will stop it from executing the rest of the middleware and go back to the exceptionhandler registered at the top. When I tried to set the StatusCode after the await _next(context) call, it interestingly had the response from the page that was requested appended by the response form the error handler.
context.Response.StatusCode = 403;
await context.Response.CompleteAsync();
//await _next(context);
return;