C# Area 雙重路由如何寫

在WebApi項目裏面web

通常除了接口, 還有管理端...一些亂七八糟的,你想展現的東西, 一種作法是分開寫:api

好比管理後臺一個項目, 而後接口一個, 而後頁面一個, 其實這樣作也能夠,可是這麼作, 不管是咱們部署的時候,ide

仍是調試的時候,都帶來了極大的不便。 項目自己 冗餘的地方也有不少, 好比說Model層, 好比說BLL, DAL這些,不少重用的方法、url

邏輯處理,這些都是沒必要要的東西。 接下來, 給你們推薦一種 Area 的方式,來解決這個問題。spa

 

 

 添加區域, 出現了對應的調試

在Areas 裏面, 會有獨立的一套 MVC blog

 

咱們先來看看, 這裏面的路由是如何寫的繼承

 

public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}接口

public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}路由

 

繼承於  Area 路由,其餘的地方, 和咱們正常的路由註冊相同。

那這段區域路由,如何添加到路由表裏, 供咱們訪問呢?

 

Global.asax

 

 

註冊 Areas 路由的地方  有一段 AreaRegistration.RegisterAllAreas(); 

是註冊全部的繼承於 AreaRegistration的路由~

 

至此, 你覺得結束了? 尚未

 

WebApi 的路由尚未註冊呢~ 

 

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

//首頁路由
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Index", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "WebApi.Areas.Luma.Controllers" }
).DataTokens.Add("Area", "Luma");

//Api路由
routes.MapRoute(
name: "apiroute",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Help", action = "Index", id = UrlParameter.Optional }
);
}
}

 

其中有一段路由比較特別, 插入了一段 namespaces 的註冊信息, 這一段內容, 就是雙路由中, 默認頁的關鍵

 

這些但願對你們能有所幫助吧~ 

 

改天再分享 webapi help 的部署~ 

相關文章
相關標籤/搜索