如何从 MVC5 中的 url 重定向

How to redirect from a url in MVC5

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

稍微有点想法可以配合RouteConfig使用,但还是没有看清楚

有人可以帮我解决这个问题吗?

操作方法是

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

路由配置是

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

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

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

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

routes.MapMvcAttributeRoutes();

和动作方法前一行

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