I'm trying to trigger an exception (handled by /Error) from a middleware in ASP.NET Core 3.1.
Exception handler is registered in Startup.cs (as shown below) without app.UseDeveloperExceptionPage(), and works well otherwise.
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");
But how do I trigger an exception (with an HTTP status code) from a middleware's Invoke method?
Update (solution): I mainly wanted to raise an exception from a custom middleware, but also pass a status code to the exception handler (/Error). I got it working with this code in the middleware:
public async Task Invoke(HttpContext context)
{
if (context?.Request?.Path.Value.StartsWith("/error"))
{
// allow processing of exception handler
await _next(context);
return;
}
// skip processing, and set status code for use in exception handler
context.SetEndpoint(endpoint: null);
context.Response.StatusCode = 503;
}
