Search code examples
asp.net-mvc-4http-redirectredirecttoaction

return RedirectToAction(...) prettier url


Is there any possible way to maintain the format of my link as defined in the RouteConfig.cs mappings when calling RedirectToAction method?

ex [just for test]:

I have this route:

routes.MapRoute(
 "Token Verification",
 "Registration/TokenVerification/{ConfernceId}/{TokenType}/{TokenId}/{Email}",
new{
  controller="Registration",
  action="TokenVerification",
  ConfernceId= 0,
  TokenType='\0',
  TokenId="",
  Email=""
 }
);

I can call this link and my action if being routed correctly:

http://localhost:49619/Registration/TokenVerification/2/R/asdasdasd/someone@somewhere.com

But if I called RedirectToAction, it will generate the following url

http://localhost:49619/Registration/TokenVerification?ConfernceId=2&TokenType=R&Email=someone%40somewhere.com

It is working also, but it is not pretty at all!

Any suggestions ?


Solution

  • Use RedirectToRoute (from MSDN) to generate urls which are in format of specified routes.

     return RedirectToRoute("Token Verification", new
            {
                ConfernceId = 0,
                TokenType = "0",
                TokenId = "0",
                Email = "0"
            });
    

    If you want to generate links, then check below perocess. use Url.RouteUrl (check MSDN resource). Say For example -

    @Url.RouteUrl("DefaultApi", new { httproute=true, controller="Albums", id=3})
    

    will generate /api/Albums/3

    In your case, it should be -

    @Url.RouteUrl("Token Verification", new
    {
        controller = "Registration",
        action = "TokenVerification",
        ConfernceId = 0,
        TokenType = "0",
        TokenId = "0",
        Email = "0"
    })
    

    And it will generate - /Registration/TokenVerification/0/0/0/0