c# - 为 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}
.
如何做到这一点?
解决方案
为此,您可以利用属性路由。为此,请使用[Route()]
数据注释装饰您的控制器方法,如下所示。
CountryController.cs
[Route("{country}")]
public IActionResult CountryPage(string country)
{
return Ok(country);
}
访问https://localhost:44376/Brazil
时,应用程序返回:
巴西
推荐阅读
- jestjs - create-react-app 和 jest - 不能在模块外使用 import 语句
- mysql - 从 SQL 中收集最近 7 天的数据并按天分组
- mysql - MySQL(低于 8.0 的版本):SELECT WHERE 多列和按最大级别分组
- python - python从单词中提取元音
- regex - 如何在文本文件中进行多行模式匹配
- c++ - 带有 void* 参数转换的函数指针
- reactjs - 离子反应动态获取屏幕宽度
- php - 需要使用 www.mydomain.com/filename/ 而不是 www.mydomain.com/file.php?id=1
- javascript - 如何使用 SinonJs 监视异步调用的数量而无需等待
- reactjs - 使用 react-pdf 生成 USING 目录