在ASP.NET MVC4中使用电子邮件地址的URL

时间:2013-05-21 14:13:16

标签: asp.net-mvc-4 asp.net-mvc-routing

我遇到的情况是我使用的网址可能包含电子邮件地址。例如:

http://MyUrl.com/Edit/Mike

http://MyUrl.com/Edit/bob@whatever.com

根据this StackOverflow question,似乎解决这个问题的简单方法是使用查询字符串。有没有办法我可以在路由规则中设置它,它将确定值是否无效并让它回退到查询字符串?

1 个答案:

答案 0 :(得分:0)

这个怎么样:

路线:

routes.MapRoute(
    name: "UserEdit",
    url: "Edit/{user}",
    defaults: new { controller = "User", action = "Edit" },
    constraints: new { user = @"[a-z0-9]+" /*Add valid characters here*/ }
);

routes.MapRoute(
    name: "UserEditWithIllegalChars",
    url: "Edit/",
    defaults: new { controller = "User", action = "Edit" }
);

该路线仅匹配/ Edit / Mike和Edit/?user=bob@whatever.com等网址。

生成URL也有效。例如

@Html.ActionLink("1", "Edit", "User", new { user = "Mike" }, new { })
@Html.ActionLink("2", "Edit", "User", new { user = "bob@whatever.com" }, new { })

生成与上述相同的网址

控制器:

public ActionResult Edit(string user)

注意: 1)您需要检查用户是否为空 2)在约束中添加有效字符,因为我不知道所有这些字符。