带有可选参数

时间:2016-07-14 09:45:25

标签: asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing .net-4.5.2

我想接受/User//User/213123

其中 213123 是参数(user_id)

这是我的 RouteConfig.cs

            routes.MapRoute(
                name: "user",
                url: "{controller}/{action}/{username}",
                defaults: new { controller = "User", action = "Index", username = UrlParameter.Optional }
            );

我的 UserController.cs

        public ActionResult Index()
        {
            ViewData["Message"] = "user index";
            return View();
        }

        [Route("user/{username}")]
        public ActionResult Index(string username)
        {
            ViewData["Message"] = "!" + username + "!";
            return View();
        }

这适用于.net-core 1.0但不适用于mvc5。我错过了什么?

谢谢

编辑:

在我的UserController.cs中使用它也不起作用(返回404):

        public ActionResult Index(string username)
        {
            if (!String.IsNullOrEmpty(username))
            {
                ViewData["Message"] = "Hello " + username;
            }
            else
            {
                ViewData["Message"] = "user index";
            }

            return View();
        } 
  

描述:HTTP 404.您正在查找的资源(或其中一个依赖项)可能已被删除,名称已更改或暂时不可用。请查看以下网址,确保拼写正确。

     

请求的网址:/ user / asd

EDIT2:

更新了 RouteConfig.cs

        routes.MapRoute(
            "userParam", "user/{username}",
          new { controller = "user", action = "IndexByUsername" },
          new { username = @"\w+" }
        );

        routes.MapRoute(
            name: "user",
            url: "user",
            defaults: new { controller = "User", action = "Index"}
        );

/User/现在使用索引作为用户名调用IndexByUsername

/User/asd仍会返回404

EDIT4 :当前代码:

RouteConfig.cs:

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

UserController.cs

public class UserController : Controller
{
    public ActionResult Index(string username)
    {
        if (!String.IsNullOrEmpty(username))
        {
            ViewData["Message"] = "Hello " + username;
        }
        else
        {
            ViewData["Message"] = "user index";
        }

        return View();
    }
}

1 个答案:

答案 0 :(得分:3)

您只需要一个带签名的操作方法

public ActionResult Index(string username)

并且在该方法中,您可以检查username的值是否为null

然后你需要路由definitiosn(注意user路由需要放在默认路由之前)

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