【问题标题】:Routing using a named parameter in the request URL在请求 URL 中使用命名参数进行路由
【发布时间】:2016-09-05 20:50:17
【问题描述】:

我正在尝试导航到路线/Account/UserProfile/{username},但我不确定我是否正确配置了路线。或者更确切地说,我不确定要在路由表中添加什么才能使这条路由正常工作。

下面是动作方法:

public IActionResult UserProfile(string username)
{
    // Do something
}

这是我正确使用的简单 GET 方法。我的问题是,即使我在 url 中提供了一个字符串,例如:/Account/UserProfile/MyUsername,字符串MyUsername 也没有发送到我的控制器。

我只有在创建应用程序时已经添加了标准路由。我需要添加什么才能使这些路由正常工作?

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

【问题讨论】:

  • 您的路线中缺少username 参数。参数名称需要匹配
  • @Nkosi 所以这样的路线:routes.MapRoute(name: 'default2', template: '{controller=Account}/{action=UserProfile}/{username}');?
  • 检查 CodeCaster 的回答。它更详细。

标签: c# asp.net asp.net-core asp.net-core-mvc


【解决方案1】:

该值将在username 键下的RouteData 中,但不会自动映射到名为username 的参数,因为该键不是已知 路由值包含该参数名称。

你可以为这个方法创建一个路由:

routes.MapRoute(
    name: "userProfileByUsername",
    template: "Account/UserProfile/{username}"),
    defaults: new { controller = "Account", action = "UserProfile" });

但这将是无稽之谈,因为它需要为每个操作方法创建一个路由。当单个路由的多次使用模式出现时,创建这样的路由是值得的,因为它使您不必多次声明相同的属性。

例如,当您想在一个控制器中声明多个操作方法时:

  • /Account/UserProfile/{username}
  • /Account/View/{username}
  • /Account/Foo/{username}
  • /Account/Bar/{username}

那么创建一条新路线会很聪明:

routes.MapRoute(
    name: "accountActionByUsername",
    template: "Account/{action}/{username}"),
    defaults: new { controller = "Account" });

对于一次性情况,或者当每个操作方法的模式不同时,您可以使用属性路由来选择特定路由:

[HttpGet("[action]/{username}"]
public IActionResult UserProfile(string username)

注意new [action] placeholder 的使用,因此您不必再将操作名称包含在字符串中。

或者你可以通过accessing the raw route data 找到值,但你真的不应该:

public IActionResult UserProfile()
{
    string username = ViewContext.RouteData.Values["username"];

    // ...
}

最后,您可以选择将用户名作为查询字符串参数:

public IActionResult UserProfile([FromQuery]string username)

发出请求 URL /Account/UserProfile?username=MyUsername

【讨论】:

  • 也可以。谢谢!
【解决方案2】:

您的路线中缺少用户名参数。参数名称需要匹配

app.UseMvc(routes => {
    routes.MapRoute(
        name: "UserProfile",
        template: "Account/UserProfile/{username}",
        defaults: { controller = "Account", action = "UserProfile" });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

【讨论】:

  • 完美运行。谢谢。
猜你喜欢
  • 2017-09-06
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
相关资源
最近更新 更多