In asp.net core mvc, how does one bind a second-level domain name to a specific controller? coremvc

Source: Internet
Author: User
Tags subdomain

In asp.net core mvc, how does one bind a second-level domain name to a specific controller? coremvc

Due to the company's work schedule, I have been studying other technologies, so I have no time to update my blog. Today I can finally stop my work and write new content.

Application Scenario: enterprise portal websites set different sections based on different content, such as Sina sports and entertainment channels. In some cases, you need to set different second-level domain names for different sections, such as Sina sports sports.sina.com.cn.

In asp.net core mvc, if we want to implement the effect of the plate, we may create different controllers for different sections (of course there are other technologies. We will not discuss the implementation methods here ), in this case, how to bind a unique second-level domain name to the Controller, for example, the Controller of the sports channel is called SportController. When you access the system through the sports.XXX.com domain name, you can directly access the SportController, the second-level domain name cannot access other controllers.

After the above scenario is completed, let's take a look at how to implement it.

The routing rule configuration is available in asp.net core mvc. The configuration is in the Startup. Configure method. The specific code is as follows:

  

app.UseMvc(routes =>{      routes.MapRoute(           name: "default",           template: "{controller=Home}/{action=Index}/{id?}",           defaults: new { area="admin"});});

Unfortunately, domain name support is not supported (I understand that if you have any questions, please correct them ). Use routes. MapRouter to register a routing rule and add it to RouteCollection. When a request comes over, RouterCollection loops through all registered IRouter objects and finds the first matched IRouter. Although the framework does not support domain name configuration rules, we can implement an IRouter by ourselves to implement the second-level domain name judgment logic in it. Here I name it SubDomainRouter temporarily. The specific implementation code is as follows:

Public class SubDomainRouter: RouteBase {private readonly IRouter _ target; private readonly string _ subDomain; public SubDomainRouter (IRouter target, string subDomain, // The second-level domain name string routeTemplate bound to the current routing rule, routeValueDictionary defaults, RouteValueDictionary constrains, IInlineConstraintResolver inlineConstraintResolver): base (routeTemplate, subDomain, inlineConstraintResolver, ults, constrai Ns, 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; // obtain the Domain Name of the current request and compare it with _ subDomain. if you do not want to wait, ignore if (string. isNullO REmpty (domain) | string. Compare (_ subDomain, domain )! = 0) {return Task. completedTask;} // If the domain name matches, verify that the access path matches the 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 );}}

From the above code, we can only see the domain name detection, but how to direct the domain name to a specific controller, this requires us to do some articles when registering this IRouter, directly on the Code:

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 <IInlineConst RaintResolver> (); 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 ?} "; // The path rule no longer contains the Controller information, but the above uses constrains to limit the Controller name routeBuilder required for searching. routes. add (new SubDomainRouter (routeBuilder. defaultHandler, domain, template, defaults, constrains, inlineConstraintResolver); return routeBuilder ;}}

Finally, we can register the corresponding rules in Startup, as shown below:

app.UseMvc(      routes =>        {            routes.MapDomainRoute("xxx.domain.com","areaname","controllername");                                    routes.MapRoute(                  name: "default",                  template: "{controller=Home}/{action=Index}/{id?}",                  defaults: new { area = "web" });        });

The implementation method may not be the best, but it has already met the basic requirements. If you have a better method, you are welcome to discuss it.

  

  

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.