


Tutorial on binding a second-level domain name to a specific controller instance
This article mainly introduces how to bind the second-level domain name to a specific controller in Asp.net Core MVC. Friends who need it can refer to it
Application scenarios: Enterprise portals will set up different sections according to different content, such as Sina has sports, entertainment channels, etc. In some cases, it is necessary to set up different second-level domain names for different sections, such as Sina Sports sports.sina.com.cn.
In asp.net core mvc, if you want to achieve the effect of sections, you may create different controllers for different sections (of course there are other technologies, the quality of the implementation is not discussed here), in In this case, how to bind a unique second-level domain name to the controller. For example, the controller corresponding to the sports channel is called SportController. When accessing the system through the sports.XXX.com domain name, directly enter the SportController and pass this second-level domain name. The domain name cannot access other controllers.
Having finished the scenario above, let’s take a look at how to implement it.
There is routing rule configuration 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, support for domain names is not supported (what I understand so far is that if there are any problems, you are welcome to correct me). Register routing rules through routes.MapRouter and add them to RouteCollection. When a request comes, RouterCollection loops through all registered IRouter objects until the first matching IRouter is found. Although the framework does not support domain name configuration rules, we can implement an IRouter ourselves to implement the logic of second-level domain name judgment. I temporarily named it SubDomainRouter. 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,//当前路由规则绑定的二级域名 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); } }
From the above code we only see domain name detection, but how to direct the domain name to a specific controller requires us to do some work when registering this IRouter and directly enter 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<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; } }
Finally, we can register the corresponding rules in Startup, as follows:
##
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; } }
The above is the detailed content of Tutorial on binding a second-level domain name to a specific controller instance. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Since Windows has become the gaming platform of choice, it's even more important to identify its gaming-oriented features. One of them is the ability to calibrate an Xbox One controller on Windows 11. With built-in manual calibration, you can get rid of drift, random movement, or performance issues and effectively align the X, Y, and Z axes. If the available options don't work, you can always use a third-party Xbox One controller calibration tool. Let’s find out! How do I calibrate my Xbox controller on Windows 11? Before proceeding, make sure you connect your controller to your computer and update your Xbox One controller's drivers. While you're at it, also install any available firmware updates. 1. Use Wind

PHP is a very popular programming language, and CodeIgniter4 is a commonly used PHP framework. When developing web applications, using frameworks is very helpful. It can speed up the development process, improve code quality, and reduce maintenance costs. This article will introduce how to use the CodeIgniter4 framework. Installing the CodeIgniter4 framework The CodeIgniter4 framework can be downloaded from the official website (https://codeigniter.com/). Down

Learning Laravel from scratch: Detailed explanation of controller method invocation In the development of Laravel, controller is a very important concept. The controller serves as a bridge between the model and the view, responsible for processing requests from routes and returning corresponding data to the view for display. Methods in controllers can be called by routes. This article will introduce in detail how to write and call methods in controllers, and will provide specific code examples. First, we need to create a controller. You can use the Artisan command line tool to create

In laravel, a controller (Controller) is a class used to implement certain functions; the controller can combine related request processing logic into a separate class. Some methods are stored in the controller to implement certain functions. The controller is called through routing, and callback functions are no longer used; the controller is stored in the "app/Http/Controllers" directory.

In the Laravel learning guide, calling controller methods is a very important topic. Controllers act as a bridge between routing and models and play a vital role in the application. This article will introduce the best practices for controller method calling and provide specific code examples to help readers better understand. First, let's understand the basic structure of controller methods. In Laravel, controller classes are usually stored in the app/Http/Controllers directory. Each controller class contains multiple

Application steps: 1. Enter the domain name registration service website, register an account and log in; 2. Select the "Domain Name Registration" service, enter the second-level domain name you want to register, and click Query; 3. If the second-level domain name has not been registered, then You can click the "Register Now" button to register; 4. On the registration information page, fill in the domain name owner's name, contact number, email and other information, and set a password; 5. Confirm the payment method and complete the payment; 6. Wait for the official Review generally takes 1-5 working days.

In the Yii framework, controllers play an important role in processing requests. In addition to handling regular page requests, controllers can also be used to handle Ajax requests. This article will introduce how to handle Ajax requests in the Yii framework and provide code examples. In the Yii framework, processing Ajax requests can be carried out through the following steps: The first step is to create a controller (Controller) class. You can inherit the basic controller class yiiwebCo provided by the Yii framework

Symfony framework is a popular PHP framework designed based on MVC (Model-View-Controller) architecture. In Symfony, controllers are one of the key components responsible for handling web application requests. Parameters in controllers are very useful when processing requests. This article will introduce how to use controller parameters in the Symfony framework. Basic knowledge of controller parameters Controller parameters are passed to the controller through routing. Routing is a mapping of URIs (Uniform Resource Identifiers) to controllers and
