Reputation: 1190
In my ASP.net Core 2.0 pipeline, I have the following two configuration entries:
app.UseIdentityServer();
app.UseMvc(...);
I wasn't sure which of these generates 401 responses, so I added some custom middleware to see if it was possible to intercept them at various stages:
app.Use(async (http, next) =>
{
if (http.Response.StatusCode == StatusCodes.Status401Unauthorized))
{
Console.WriteLine("intercept!");
}
});
This code would fire after if placed after UseIdentityServer()
, but not with the 401, and would not fire at all if placed after UseMvc()
in a 401 scenario. That is, UseMvc()
appears to be ending the pipeline.
Since in one case the error hasn't happened, and in the other it's never reached, how can I go about intercepting these 401s? (And potentially rewriting them)
I also tried a try-catch around the pipeline continuation, placed very early in the pipeline, but this didn't fire either:
app.Use(async (http, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
Console.WriteLine("intercept!");
}
});
Any ideas on how I can put that intercept in place?
Upvotes: 3
Views: 3043
Reputation: 987
Use this middleware before anything else :
app.Use(async (context, next) =>
{
await next.Invoke();
if(context.Response.StatusCode == StatusCodes.Status404NotFound)
{
await context.Response.WriteAsync("You seem to have mistyped the url");
}
});
There won't be any exception for Not found. Default value of StatusCode for a context response is 404. If no middleware modifies the response , 404 will be returned to the client. In this case, we have set up a middleware that allows other middlewares to process the request first by awaiting next.Invoke()..Now, while returning back it checks if StatusCode is still 404 and writes a "you seem to have mistyped the url" message.
Upvotes: 4