MVC路由约束随机a-zA-Z

时间:2015-02-25 10:18:01

标签: c# regex asp.net-mvc asp.net-mvc-4

我喜欢创建注册这样的路线:

User/{^[a-zA-Z]+$}/{controller}/{action}/{id}

这就是网址的样子:

/User/myUser/Product/Action

所以我在AreaRegistration中注册了一条路线。约束应该只允许单词。

context.MapRoute(
    "Customer_Default",
    "User/{^[a-zA-Z]+$}/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional }
);
  1. 我的约束是否正确。
  2. 如何使用RedirectToAction路线重定向到此?
  3. 在Action中获取用户名的最佳方法是什么?正则表达式...?

2 个答案:

答案 0 :(得分:1)

您需要使用constraints

MapRoute()参数
context.MapRoute(
    "Customer_Default",
    "User/{username}/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    constraints: new { username= @"^[a-zA-Z]+$" }
);

那你的行动就是这样:

public ActionResult ActionName(string username, int id)

答案 1 :(得分:0)

  1. 我认为使用约束的正确方法是: routes.MapRoute(name:“Customer_Default”,             url:“用户/ {username} / {controller} / {action} / {id}”,             默认值:new {action =“Index”,id = UrlParameter.Optional},             约束:new {username =“^ [a-zA-Z] + $”});
  2. 我不知道如何重定向到这条路线..
  3. 我认为您最好创建一个登录模型,并使用一致的类型来传递用户名和密码。