user5947858
user5947858

Reputation: 23

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 ?

Upvotes: 2

Views: 820

Answers (2)

Shahzad Hassan
Shahzad Hassan

Reputation: 1003

I think it's quite easy to do within your controller if you don't want to use the middleware. Another benefit you will get is that you can set the RouteName for all other routes and simply redirect to the route using RedirectToRoute method. So within your UrlToken action:

[Route("[action]"]
public IActionResult SingleSignOn(string urlToken)
{
    If (!string.IsNullOrWhitespace(urlToken))
    {
        return RedirectToRoute("RouteName"):
    }
}

For the above to work you have to specify the RouteName for other actions either by using AttributeRouting or define globally in the startup:

[Route("[action]", Name = "otherroute")]
public IActionResult OtherAction(string param1, string param 2)
{
    //...
}

So simply replace the "RouteName" in your SingleSignOn action to "otherroute" and it will work. If you need to pass the route parameters to the "otherroute" you can use one of the overloads of RedirectToRoute method. I hope this helps.

Upvotes: 0

itminus
itminus

Reputation: 25360

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

Upvotes: 1

Related Questions