ASP.NET 在区域中包含 Id 时,核心 MVC 虚拟路径生成不正确
ASP.NET Core MVC virtual path generation incorrect when including an Id within an Area
我正在 ASP.NET Core 2.0 MVC 应用程序中工作,我正在尝试使用路由信息构建 URL。只要我坚持使用 Area、Controller 和 Action,一切都很好。一旦我尝试使用 Id,路径就会返回错误
当我包含除 id 之外的所有内容时,我得到了我期望的结果
<a asp-area="Admin" asp-controller="Users" asp-action="Detail">User detail</a>
或从 UsersController 内部
Url.Action("Detail")
产生
http://localhost:55556/Admin/Users/Detail
当我包含 id 时
<a asp-area="Admin" asp-controller="Users" asp-action="Detail" asp-route-id="1">User detail</a>
或
Url.Action("Detail", new { id = 1 })
我只得到
http://localhost:55556/1
我的路线是这样的
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
谁能看出我错在哪里?
更新
好像跟Area有关。当我离开该区域时,它会产生我所期望的
Url.Action("Detail", "Users", new { id = 1 })
产生
/Users/Detail/1
尽管实际上并不存在。虽然当我添加区域
Url.Action("Detail", "Users", new { id = 1, area = "Admin" })
我明白了
/1
有没有其他人遇到区域路由问题?
我明白了。我在操作上有一个不正确的 [HttpGet]
属性。
我有
[HttpGet("{id:int}")]
public ActionResult Detail(int id)
{
var user = _userRepository.GetUserById(id);
var model = Mapper.Map<User, UserDetailModel>(user);
return View(model);
}
没有意识到我在属性中设置的路由完全覆盖了默认值,而不仅仅是应用于参数
我删除了 ("{id:int}")
并且一切正常
我正在 ASP.NET Core 2.0 MVC 应用程序中工作,我正在尝试使用路由信息构建 URL。只要我坚持使用 Area、Controller 和 Action,一切都很好。一旦我尝试使用 Id,路径就会返回错误
当我包含除 id 之外的所有内容时,我得到了我期望的结果
<a asp-area="Admin" asp-controller="Users" asp-action="Detail">User detail</a>
或从 UsersController 内部
Url.Action("Detail")
产生
http://localhost:55556/Admin/Users/Detail
当我包含 id 时
<a asp-area="Admin" asp-controller="Users" asp-action="Detail" asp-route-id="1">User detail</a>
或
Url.Action("Detail", new { id = 1 })
我只得到
http://localhost:55556/1
我的路线是这样的
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
谁能看出我错在哪里?
更新
好像跟Area有关。当我离开该区域时,它会产生我所期望的
Url.Action("Detail", "Users", new { id = 1 })
产生
/Users/Detail/1
尽管实际上并不存在。虽然当我添加区域
Url.Action("Detail", "Users", new { id = 1, area = "Admin" })
我明白了
/1
有没有其他人遇到区域路由问题?
我明白了。我在操作上有一个不正确的 [HttpGet]
属性。
我有
[HttpGet("{id:int}")]
public ActionResult Detail(int id)
{
var user = _userRepository.GetUserById(id);
var model = Mapper.Map<User, UserDetailModel>(user);
return View(model);
}
没有意识到我在属性中设置的路由完全覆盖了默认值,而不仅仅是应用于参数
我删除了 ("{id:int}")
并且一切正常