【问题标题】:Shortening URL params with MVC routing使用 MVC 路由缩短 URL 参数
【发布时间】:2009-08-15 13:45:58
【问题描述】:

我有一个类似这样的网址:

example.com/profile/publicview?profileKey=5

我想用路由把它缩短到这个程度

example.com/profile/5

我该怎么做?

这是我的尝试:

routes.MapRoute(
    "Profile", "Profile/{profileKey}", 
    new { controller = "Profile", action = "PublicView", profileKey ="" }
);

但是他产生了这个错误:

参数字典包含一个 参数“profileKey”的空条目 不可为空的类型'System.Int32' 对于方法 'System.Web.Mvc.ActionResult 公共视图(Int32)'在 'Website.Controllers.ProfileController

动作方法

public ActionResult PublicView(int profileKey)
  {
        //stuff
  }

【问题讨论】:

  • 您能否将代码发布到您的 PublicView() 操作方法中引发异常的地方?
  • 完成。没有包括方法体,因为它没有那么远。
  • 试试我和 Mike 同时给出的答案。

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


【解决方案1】:

在控制器上更改 PublicView(int? profileKey)

回复评论

是的,但是由于您在路由中的默认值为null,因此您需要处理它。否则,请更改路由中的默认值。

可能

这可能无济于事,但值得一试。这是我的网站的代码:

        routes.MapRoute(
            "freebies",                                              // Route name
            "freebies/{page}",                           // URL with parameters
            new { controller = "Home", action = "Freebies", page = 1 }  // Parameter defaults
        );

还有链接:

http://localhost/freebies/2

这很好用。

【讨论】:

  • 它将允许路由正常工作。然后,您需要做的就是在操作中执行 profileKey.HasValue。如果是,那么你有一个 int。否则,您可以重定向到其他地方,或者抛出错误。
  • 这个答案告诉我如何停止错误方法的异常。如果路由正确,则不应首先发生异常。
【解决方案2】:

当且仅当您始终在您的 url 中包含一个整数值时,您的路由和操作方法是正常的,如 example.com/profile/5时间>。 (我假设这条路线是在默认路线之上定义的)

您定义的是一个路由,如果 url 中未提供 profileKey,则默认为空字符串,并且在您的操作方法中,您尝试将此值绑定到不可为空的整数,所以如果您正在尝试 example.com/profile 或 example.com/profile/not-an-int 这将引发您报告的异常。您的路线将为 profileKey 分配一个空字符串,但您的操作方法无法将其转换为整数。作为 Martin pointed out,解决此问题的一种方法是使用可为空的 int 代替。另一种解决方案是在您的路由中将此值默认为整数。

如果您仍然收到错误,请确保您请求的实际 URL 正确且包含 profileKey。我知道有时在使用默认的 html 和/或 url 帮助程序时,我在传递 routeValues 时出错,最终呈现链接或发布到我期望的以外的 url...

希望有帮助

【讨论】:

    【解决方案3】:

    那是你唯一的路线吗?如果不是,则可能是另一个路由(之前声明的)首先匹配,并且没有正确获取 profileKey 参数。

    【讨论】:

    • 我读到可能是这个,所以 iv 注释掉了所有其他路由,所以我只有这个,然后是默认的。但它没有帮助。
    【解决方案4】:

    试试这个(未经测试的)代码

    routes.MapRoute(
        "Profile", "Profile/{profileKey}", 
        new { controller = "Profile", action = "PublicView" }
    );
    

    【讨论】:

    • 不会导致同样的异常。我能想到的最好的方法是 routes.MapRoute("Profile", "Profile", new { controller = "Profile", action = "PublicView" });但这会产生一个 example.com/profile?profileKey=5 的 url,它仍然不是完美的。
    • 我测试过它应该可以工作。你会发布你的方法签名吗?
    猜你喜欢
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多