【问题标题】:Url with email address in ASP.NET MVC4ASP.NET MVC4 中带有电子邮件地址的 URL
【发布时间】:2013-05-21 23:18:56
【问题描述】:

我有一种情况,我使用的 URL 可能包含电子邮件地址。例如:

http://MyUrl.com/Edit/Mike

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

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

【问题讨论】:

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


    【解决方案1】:

    这个怎么样:

    路线:

    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。

    生成 URL 也可以。例如

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

    生成与上述相同的 URL

    控制器:

    public ActionResult Edit(string user)
    

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

    【讨论】:

    • 谢谢,我不知道约束。
    猜你喜欢
    • 2013-12-22
    • 2017-08-31
    • 2010-10-03
    • 1970-01-01
    • 2017-09-15
    • 2010-09-16
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多