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

编程入门 行业动态 更新时间:2024-10-19 19:42:38
本文介绍了ASP Core 2.0管道中的Intercept 401错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

In my ASP 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错误

本文发布于:2023-11-14 00:15:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:道中   错误   Core   ASP   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!