Asp.net-Core-Mvc

‘:exists’ 在路由模板上做了什麼?

  • August 4, 2018

我閱讀了一篇文章,其中討論瞭如何為視圖設置自定義路徑。

http://www.c-sharpcorner.com/article/expanding-razor-view-location-and-sub-areas-in-asp-net-core/

路由程式碼設置不清楚。

app.UseMvc(routes =>
{
   routes.MapRoute(
       name: "subAreaRoute",
       template: "{area:exists}/{subarea:exists}/{controller=Home}/{action=Index}/{id?}");
   routes.MapRoute(
       name: "areaRoute",
       template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
   routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");
});

這是做什麼的:{area:exists}?它在檢查什麼?

exists適用KnownRouteValueConstraint於路線。它使路由僅在找到具有相應路由值的操作時才匹配。這意味著它僅在它針對現有區域的情況下才會匹配路由{area:exists}

你可以在這裡看到它的原始碼:https ://github.com/aspnet/Mvc/blob/rel/2.0.0/src/Microsoft.AspNetCore.Mvc.Core/Routing/KnownRouteValueConstraint.cs 。

如果不使用exists約束,它會起作用,但使用它的要點是,如果它接收到/SomeArea/Home/Index之類的URL,它將首先嘗試第一個路由模板。它首先檢查是否有 area=SomeArea 的操作。然後它檢查它是否有 subarea=Home。此時它可能會認為這樣的操作不存在,因此它拒絕匹配。然後它會嘗試下一個匹配的模板(在典型設置中)。那麼當然如果沒有區域SomeArea,它會嘗試最後一個路由模板。它實際上會匹配,認為 controller=SomeArea,action=Home,id=Index。未找到此類操作 = 404。

主要區別在於匹配第一個模板的 URL 將獲得 404 而沒有約束。

使用該約束,如果 URL 在與該模板一起使用時沒有匹配的操作,則不會選擇該模板。然後框架將嘗試下一個路由模板來定位操作。

引用自:https://stackoverflow.com/questions/44260468