簡體   English   中英

Url.Action 不輸出自定義映射控制器路由

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM