简体   繁体   English

ASP.net Core 2.0管道中的Intercept 401错误

[英]Intercept 401 error in ASP.net Core 2.0 pipeline

In my ASP.net Core 2.0 pipeline, I have the following two configuration entries: 在我的ASP.net Core 2.0管道中,我具有以下两个配置条目:

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: 我不确定其中哪个会产生401响应,因此我添加了一些自定义中间件,以查看是否有可能在各个阶段拦截它们:

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. 如果将其放置在UseIdentityServer() ,则将触发此代码,但不会与401一起触发如果在401场景中,将其放置在UseMvc()之后则不会触发。 That is, UseMvc() appears to be ending the pipeline. 也就是说, UseMvc()似乎正在结束管道。

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? 由于在一种情况下没有发生错误,而在另一种情况下从未发生,我该如何继续拦截这些401? (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: 我还尝试了围绕管道延续的try-catch,将其放置在管道的早期,但这也没有触发:

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? 关于如何进行拦截的任何想法?

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. 上下文响应的StatusCode的默认值为404。如果没有中间件修改响应,则404将返回给客户端。 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. 在这种情况下,我们设置了一个中间件,该中间件允许其他中间件首先通过等待next.Invoke()来处理请求。网址”消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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