這篇文章主要介紹了Asp.net Core MVC中怎麼把二級網域綁定到特定的控制器上,需要的朋友可以參考下
應用場景:企業入口網站會根據內容不同,設定不同的板塊,如新浪有體育,娛樂頻道,等等。有的情況下需要為不同的板塊設置不同的二級域名,如新浪體育sports.sina.com.cn。
在asp.net core mvc中,如果要實現板塊的效果,可能會給不同的板塊建立不同的控制器(當然也有其他的技術,這裡不討論實現方式的好壞),在這種情況下,如何給控制器綁定上獨有的二級域名,例如體育頻道對應的控制器叫SportController,透過sports.XXX.com域名存取系統的時候,直接進入SportController,並且透過這個二級網域無法存取其他的控制器。
上面說完場景了,下面來看下如何實現。
在asp.net core mvc中有路由規則配置,配置的地方在Startup.Configure方法中,具體程式碼如下:
app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}", defaults: new { area="admin"}); });
遺憾的是不支援對網域的支援(我目前了解的是,如果有問題,歡迎大家指正)。透過routes.MapRouter註冊路由規則,並加入到RouteCollection中,當某個請求過來後,RouterCollection循環所有註冊好的IRouter對象,找到第一個匹配的IRouter為止。雖然框架不支援網域設定規則,但我們可以自己去實作一個IRouter,在裡面實作二級網域判斷的邏輯,我這裡暫時取名為SubDomainRouter,具體實作程式碼如下:
##
public class SubDomainRouter : RouteBase { private readonly IRouter _target; private readonly string _subDomain; public SubDomainRouter( IRouter target, string subDomain,//当前路由规则绑定的二级域名 string routeTemplate, RouteValueDictionary defaults, RouteValueDictionary constrains, IInlineConstraintResolver inlineConstraintResolver) : base(routeTemplate, subDomain, inlineConstraintResolver, defaults, constrains, new RouteValueDictionary(null)) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (subDomain == null) { throw new ArgumentNullException(nameof(subDomain)); } _subDomain = subDomain; _target = target; } public override Task RouteAsync(RouteContext context) { string domain = context.HttpContext.Request.Host.Host;//获取当前请求域名,然后跟_subDomain比较,如果不想等,直接忽略 if (string.IsNullOrEmpty(domain) || string.Compare(_subDomain, domain) != 0) { return Task.CompletedTask; } //如果域名匹配,再去验证访问路径是否匹配 return base.RouteAsync(context); } protected override Task OnRouteMatched(RouteContext context) { context.RouteData.Routers.Add(_target); return _target.RouteAsync(context); } protected override VirtualPathData OnVirtualPathGenerated(VirtualPathContext context) { return _target.GetVirtualPath(context); } }從上面的程式碼我們只看到了網域偵測,但是如何把網域導向到特定的控制器上,這就需要我們在註冊這個IRouter的時候做些文章,直接上程式碼:
public static class RouteBuilderExtensions { public static IRouteBuilder MapDomainRoute( this IRouteBuilder routeBuilder,string domain,string area,string controller) { if(string.IsNullOrEmpty(area)||string.IsNullOrEmpty(controller)) { throw new ArgumentNullException("area or controller can not be null"); } var inlineConstraintResolver = routeBuilder .ServiceProvider .GetRequiredService<IInlineConstraintResolver>(); string template = ""; RouteValueDictionary defaults = new RouteValueDictionary(); RouteValueDictionary constrains = new RouteValueDictionary(); constrains.Add("area", area); defaults.Add("area", area); constrains.Add("controller", controller); defaults.Add("controller", string.IsNullOrEmpty(controller) ? "home" : controller); defaults.Add("action", "index"); template += "{action}/{id?}";//路径规则中不再包含控制器信息,但是上面通过constrains限定了查找时所要求的控制器名称 routeBuilder.Routes.Add(new SubDomainRouter(routeBuilder.DefaultHandler, domain, template, defaults, constrains, inlineConstraintResolver)); return routeBuilder; } }最後我們就可以在Startup中註冊對應的規則,如下:
public static class RouteBuilderExtensions { public static IRouteBuilder MapDomainRoute( this IRouteBuilder routeBuilder,string domain,string area,string controller) { if(string.IsNullOrEmpty(area)||string.IsNullOrEmpty(controller)) { throw new ArgumentNullException("area or controller can not be null"); } var inlineConstraintResolver = routeBuilder .ServiceProvider .GetRequiredService<IInlineConstraintResolver>(); string template = ""; RouteValueDictionary defaults = new RouteValueDictionary(); RouteValueDictionary constrains = new RouteValueDictionary(); constrains.Add("area", area); defaults.Add("area", area); constrains.Add("controller", controller); defaults.Add("controller", string.IsNullOrEmpty(controller) ? "home" : controller); defaults.Add("action", "index"); template += "{action}/{id?}";//路径规则中不再包含控制器信息,但是上面通过constrains限定了查找时所要求的控制器名称 routeBuilder.Routes.Add(new SubDomainRouter(routeBuilder.DefaultHandler, domain, template, defaults, constrains, inlineConstraintResolver)); return routeBuilder; } }
以上是二級域名綁到特定的控制器實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。

C#.NET應用的測試策略包括單元測試、集成測試和端到端測試。 1.單元測試確保代碼的最小單元獨立工作,使用MSTest、NUnit或xUnit框架。 2.集成測試驗證多個單元組合的功能,常用模擬數據和外部服務。 3.端到端測試模擬用戶完整操作流程,通常使用Selenium進行自動化測試。

C#高級開發者面試需要掌握異步編程、LINQ、.NET框架內部工作原理等核心知識。 1.異步編程通過async和await簡化操作,提升應用響應性。 2.LINQ以SQL風格操作數據,需注意性能。 3..NET框架的CLR管理內存,垃圾回收需謹慎使用。

C#.NET面試問題和答案包括基礎知識、核心概念和高級用法。 1)基礎知識:C#是微軟開發的面向對象語言,主要用於.NET框架。 2)核心概念:委託和事件允許動態綁定方法,LINQ提供強大查詢功能。 3)高級用法:異步編程提高響應性,表達式樹用於動態代碼構建。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具