C# 端点匹配后在中间件中重写路由
我目前正在使用中间件编写一个速率限制器,它基于每个用户。当某个用户的速率限制超过时,我想将路由重写到我的429页面,该页面告诉用户他超过了速率限制 这是我当前的中间件的一个示例:C# 端点匹配后在中间件中重写路由,c#,asp.net-core,routes,asp.net-core-mvc,asp.net-core-3.1,C#,Asp.net Core,Routes,Asp.net Core Mvc,Asp.net Core 3.1,我目前正在使用中间件编写一个速率限制器,它基于每个用户。当某个用户的速率限制超过时,我想将路由重写到我的429页面,该页面告诉用户他超过了速率限制 这是我当前的中间件的一个示例: 公共类中间件:imidware { 公共任务InvokeAsync(HttpContext上下文,RequestDelegate next) { if(超过ratelimited(context.User)) { context.Request.Path=“/Home/Ratelimit”; } 返回next.Invo
公共类中间件:imidware
{
公共任务InvokeAsync(HttpContext上下文,RequestDelegate next)
{
if(超过ratelimited(context.User))
{
context.Request.Path=“/Home/Ratelimit”;
}
返回next.Invoke(上下文);
}
已超出公共bool ratelimited(ClaimsPrincipal用户)
{
//...
}
}
现在转到我的配置方法:
public void配置(IApplicationBuilder应用程序,IWebHostEnvironment环境)
{
// ...
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimit();//这将RateLimitMiddleware类添加到中间件中。
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
现在来看实际问题,在
UseRouting
之后,您不能在任何中间件中重写路由。因为它是决定选择哪个端点的实际方法。因此,以后是否可以重写路由
但是,请注意,我不想将用户重定向到rate limit视图。此外,我不能只是在链中向上移动中间件,因为我需要设置HttpContext.User