首页 > 解决方案 > 当 URL 包含特定查询参数时,如何绕过所有其他 MVC 路由?

问题描述

我需要捕获包含URLToken查询参数的任何请求,例如在此 URL 中:

http://test.server.com/product?URLToken=4abc4567ed ...

并将其重定向到特定的控制器和操作。

我尝试设置各种带有约束的路线,包括如下所示的路线。

app.UseMvc(routes =>
{
    routes.MapRoute(
           name: "ssocapture",
           template: "{*stuff}",
           defaults: new { controller = "Account", action = "SingleSignOn" },
           constraints: new { stuff= @"URLToken=" }  );

    routes.MapRoute(
           name: "default",
           template: "{controller=home}/{action=index}/{id?}");
}); 

SingleSignOn 开头的断点永远不会通过此规则命中(以下到操作的直接链接确实命中了断点,所以我知道控制器和操作正在工作)。

http://test.server.com/account/singlesignon?URLToken=4abc4567ed ...

我错过了什么/做错了什么?

标签: c#asp.net-coreasp.net-core-mvcasp.net-core-routing

解决方案


路线不是为此而设计的。要实现您的目标,只需在之前添加一个中间件UseMVC()

app.Use((ctx , next)=>{
    var token = ctx.Request.Query["URLToken"].FirstOrDefault();
    if(token!=null){
        ctx.Response.Redirect($"somecontroller/specificaction/{token}"); // redirect as you like
        // might be :
        //  ctx.Response.Redirect($"Account/SingleSignOn/{token}");
    }
    return next();
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

推荐阅读