【问题标题】:Url.Action not outputting custom mapped controller routeUrl.Action 未输出自定义映射控制器路由
【发布时间】:2021-12-07 14:05:00
【问题描述】:

这适用于 .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 })

而不是将这些网址呈现为/Admin/Agencies/Types/Create/Admin/Agencies/Types/Edit/id,它仍在使用/Admin/AgencyTypes/Create/Admin/AgencyTypes/Edit 的网址

要让Url.Action 使用我的自定义路线,我还需要做些什么吗?还是我绘制路线的方式有问题?

【问题讨论】:

  • Url.RouteUrl
  • 您应该在一般 MapControllerRoute 之前添加更具体的 MapControllerRoute
  • @AliZeinali 你是什么意思,就像我每个动作都需要一个?

标签: c# .net asp.net-mvc .net-core


【解决方案1】:

先添加更具体的路线:

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?} 这样的一般模式时,它将位于列表的第一个,因此它始终是第一个匹配的模式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多