Search code examples
visual-studio-2013asp.net-mvc-5routeconfig

How to redirect from a url in MVC5


I have a url which says www.test.com/12345. When the user hit this url, he should be redirected to respective action method where "12345" accepts as its parameter.

I have a slight idea that can be used with RouteConfig but still no clear picture.

Can any one help me on this please?

Action method is

[HttpPost]
public ActionResult DetailsByCode(string code)
{    
     IEnumerable<IProductListDto> prdctListDto = _productListDetails.GetProductListByCode(accessCode);
     Return "success";
}

and routeconfig is

routes.MapRoute(
     name: "Accesscode",
     url: "{Areas}/{controller}/{action}/{id}",
     defaults: new { Areas = "Student", controller = "Student", action = "DetailsByCode", id = string.Empty }
 ); 

My complete routeconfig.cs is

  public static void RegisterRoutes(RouteCollection routes)
    { 
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "DetailsByCodeRoute",
            url: "{Areas}/{controller}/{action}/{id}",
            defaults: new { Areas = "Student", controller = "Student", action = "DetailsByCode" }
          );

        routes.MapRoute(
            name: "Accesscode",
            url: "{Areas}/{controller}/{action}/{id}",
            defaults: new { Areas = "Student", controller = "Student", action = "DetailsByCode", id = string.Empty }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",                
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }               
        );

        routes.MapRoute(
            name: "ChangePassword",
            url: "{Areas}/{controller}/{action}/{id}",
            defaults: new { Areas = "User", controller = "User", action = "ChangePassword", id = string.Empty }
        );
        routes.MapRoute(
           name: "PasswordReset",
           url: "{Areas}/{controller}/{action}/{id}",
           defaults: new { Areas = "User", controller = "User", action = "PasswordReset", id = string.Empty }
       );

Solution

  • Instead of adding new route i added one line in Routeconfig.cs which is for Enable Attribute routing.

    routes.MapMvcAttributeRoutes();
    

    and one line before the action method

    [Route("{accesscode:int}")]