Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-routing

How to bypass all other MVC routes when a URL contains a specific query parameter?


I need to capture any request that contains a query parameter of URLToken, such as in this URL:

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

and redirect it to a specific controller and action.

I have tried setting up various routes with constraints including the one shown below.

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

Break points at the beginning of SingleSignOn are never hit via this rule (the following direct link to the action does hit the break point, so I know the controller and action are working).

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

What I am I missing / doing wrong ?


Solution

  • Routes are not designed to do that. To achieve your goals, simply add a middleware before 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?}");
    });