如何从MVC5中的URL重定向

时间:2016-01-18 06:32:00

标签: visual-studio-2013 asp.net-mvc-5 routeconfig

我有一个网址,上面写着www.test.com/12345。当用户点击此网址时,应将其重定向到相应的操作方法,其中“12345”接受其作为参数。

我有一点想法可以与RouteConfig一起使用,但仍然没有清晰的图片。

有人可以帮我吗?

行动方法是

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

和routeconfig是

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

我的完整routeconfig.cs是

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

2 个答案:

答案 0 :(得分:0)

在您的情况下,您可以使用路线约束。

例如阅读这篇文章。 http://www.c-sharpcorner.com/UploadFile/ff2f08/custom-route-constraints-in-Asp-Net-mvc-5/

答案 1 :(得分:0)

我没有添加新路由,而是在Routeconfig.cs中添加了一行,用于启用属性路由。

routes.MapMvcAttributeRoutes();

和操作方法之前的一行

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