首页 > 解决方案 > 为 id 参数和 action/id 创建 MVC 路由

问题描述

这个 URLwww.mysite.com/Brazil应该路由到这个控制器:

public async Task<IActionResult> CountryPage(string countryName)

countryName 应该是Brazil

我尝试使用此自定义路线:

routes.MapRoute(
    "Country",
    "{id}",
    new { controller = "Countries", action = "CountryPage", id = "{id}" });

当我的控制器是:

public async Task<IActionResult> CountryPage(string id)

但我在 id 中得到的只是{id}.

如何做到这一点?

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

解决方案


为此,您可以利用属性路由。为此,请使用[Route()]数据注释装饰您的控制器方法,如下所示。

CountryController.cs

[Route("{country}")]
public IActionResult CountryPage(string country)
{
    return Ok(country);
}

访问https://localhost:44376/Brazil时,应用程序返回:

巴西


推荐阅读