这适用于 .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
,所以我在 Startup 中有这个:
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 })
而不是将这些 url 呈现为/Admin/Agencies/Types/Create
and /Admin/Agencies/Types/Edit/id
,它仍然使用/Admin/AgencyTypes/Create
and的 url/Admin/AgencyTypes/Edit
我还需要做些什么来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?}
,它将位于列表的第一个,因此它始终是第一个匹配的模式