【问题标题】:Create MVC route for id parameter and for action/id为 id 参数和 action/id 创建 MVC 路由
【发布时间】:2019-07-18 01:24:36
【问题描述】:

这个 URL www.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-core routes


    【解决方案1】:

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

    CountryController.cs

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

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

    巴西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多