【问题标题】:Vanity Url, reading an entered string instead of intVanity Url,读取输入的字符串而不是 int
【发布时间】:2023-03-08 04:21:01
【问题描述】:

我正在尝试允许 Vanity Urls,但我遇到了如果我输入的问题

XXXX/User/Profile/Test

而不是

xxxx/User/Profile/224

它无法读取字符串。

我目前的ActionResult如下:

public ActionResult Profile(int ID = -1, string VanityID = null)
    {
        if (VanityID == null)
        {
            ppUser viewerChoice = DB.ppUser_GetUserByPersonID(ID);
            return View(viewerChoice);
        }
        else
        {
            ppUser viewerChoice = DB.ppUser_GetUserByVanityID(VanityID);
            return View(viewerChoice);
        }
    }

如果在 URL 中输入一个 int,它将接受 int Id,但如果输入一个字符串,则不会接受任何内容并抛出错误,因为 ID 被读取为 -1。

我也一直在尝试使用 2 个操作结果,如下所示:

public ActionResult Profile(int ID)
    {
            ppUser viewerChoice = DB.ppUser_GetUserByPersonID(ID);
            return View(viewerChoice);
    }

    public ActionResult Profile(string ID)
    {
        ppUser viewerChoice = DB.ppUser_GetUserByVanityID(ID);
        return View(viewerChoice);
    }

但是当我尝试调用任一 ActionResult 时,它会向我抛出 AmbiguousMatchException 错误。

这就是 routes.Maproute 如果它也有帮助的话。

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { controller = @"[^\.]*" }, // Parameter constraints
            new string[] { typeof(MvcApplication).Namespace + ".Controllers" }
        );

【问题讨论】:

  • 我建议您创建两条单独的路线(有约束)。一个接受 {id} 并验证它是一个整数,另一个接受 {name} 并验证它是一个字符串。那么您的部分操作将是字符串名称而不是字符串 ID。

标签: asp.net-mvc-3 routing actionresult


【解决方案1】:

我想你快到了。试试setting a constraint 的id:

new { ID = @"\d+" }

这将保证,如果您尝试访问 XXXX/User/Profile/Test,您的操作不会被命中,因为 Test 并不是真正的 id。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多