![](/img/trans.png)
[英]Url.Action is not working with routes specified in controller using route annotation
[英]Url.Action not outputting custom mapped controller route
这适用于 .NET 5.0 MVC Web 应用程序。
我有一个控制器来管理我网站管理区域中的代理类型:
[Area("Admin")]
public class AgencyTypesController : Controller
{
public async Task<IActionResult> Index()
{
...
}
public async Task<IActionResult> Create()
{
...
}
public async Task<IActionResult> Edit(Guid id)
{
...
}
}
当前 url 位于/Admin/AgencyTypes
,但我希望它是/Admin/Agencies/Types
,所以我在我的启动中有这个:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "agencytypes",
pattern: "{area:exists}/Agencies/Types/{action=Index}",
defaults: new { controller = "AgencyTypes", action = "Index" }
);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
当我导航到/Admin/Agencies/Types
,我的路由似乎工作正常,它命中了 AgencyTypesController 中的 Index 操作。
问题是我的页面有指向 Create 和 Edit 方法的链接,使用Url.Action
@Url.Action("Create", "AgencyTypes", new { Area = "Admin" })
@Url.Action("Edit", "AgencyTypes", new { Area = "Admin", id = ID })
而不是这些网址呈现为/Admin/Agencies/Types/Create
和/Admin/Agencies/Types/Edit/id
,它仍然使用/Admin/AgencyTypes/Create
和/Admin/AgencyTypes/Edit
的网址
我还需要做些什么才能让Url.Action
与我的自定义路由Url.Action
工作? 还是我绘制路线的方式有问题?
首先添加更具体的路线:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "agencytypes",
pattern: "{area:exists}/Agencies/Types/{action=Index}",
defaults: new { controller = "AgencyTypes", action = "Index" }
);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
这是因为当它创建一个 url 时,它会通过你定义的路由并找到第一个匹配的路由。
因此,当您首先添加像{area:exists}/{controller=Home}/{action=Index}/{id?}
这样的一般模式时,它将位于列表的第一个,因此它始终是第一个模式哪个匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.