ASP.net Core 2.0管道中的Intercept 401错误 [英] Intercept 401 error in ASP.net Core 2.0 pipeline

查看:227
本文介绍了ASP.net Core 2.0管道中的Intercept 401错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.net Core 2.0管道中,有以下两个配置条目:

In my ASP.net Core 2.0 pipeline, I have the following two configuration entries:

app.UseIdentityServer();
app.UseMvc(...);

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

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!");
    }
});

如果放置在UseIdentityServer()之后,此代码将在后面触发,但不与401一起触发,如果在401场景中放置在UseMvc()之后,则根本不会触发 .也就是说,UseMvc()似乎正在结束管道.

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.

由于在一种情况下未发生错误,而在另一种情况下从未发生错误,我该如何继续拦截这些401? (并可能会重写它们)

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?

推荐答案

请先使用此中间件:

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");
    }              
});

未找到"将不会有任何异常.上下文响应的StatusCode的默认值为404.如果没有中间件修改响应,则404将返回给客户端.在这种情况下,我们设置了一个中间件,该中间件允许其他中间件首先通过等待next.Invoke().. Now来处理请求.现在,在返回该中间件时,它会检查StatusCode是否仍为404并写上您似乎输入了错误的网址"消息.

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.

这篇关于ASP.net Core 2.0管道中的Intercept 401错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆