Home Backend Development C#.Net Tutorial How to bind the second-level domain name to a specific controller in asp.net core mvc

How to bind the second-level domain name to a specific controller in asp.net core mvc

Jun 26, 2017 pm 03:19 PM
asp.net core secondary domain how binding

Due to the company’s work arrangements, I have been studying other technologies, so I have not had time to update the blog. Today I can finally stop what I am doing and write some new content.

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 said 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"});
});
Copy after login

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);
        }
    }
Copy after login

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;
        }
}
Copy after login

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

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

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

 

 

 

The above is the detailed content of How to bind the second-level domain name to a specific controller in asp.net core mvc. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable Core Isolation's memory integrity feature in Windows 11 How to enable Core Isolation's memory integrity feature in Windows 11 May 10, 2023 pm 11:49 PM

Microsoft's Windows 11 2022 Update (22H2) enables CoreIsolation's memory integrity protection by default. However, if you are running an older version of the operating system, such as Windows 11 2022 Update (22H1), you will need to turn this feature on manually. Turn on CoreIsolation's Memory Integrity feature in Windows 11 For users who don't know about Core Isolation, it's a security process designed to protect basic core activities on Windows from malicious programs by isolating them in memory. This process, combined with the memory integrity feature, ensures

Can two WeChat accounts be bound to the same bank card? Can two WeChat accounts be bound to the same bank card? Aug 25, 2023 pm 03:13 PM

Two WeChat accounts cannot be bound to the same bank card. Bind a bank card to a WeChat account: 1. Open the WeChat application, click the "Me" option, and then select the "Pay" option; 2. Select the "Add Bank Card" option and enter the bank card information as prompted; 3. Once the bank card is successfully bound, users can use the bank card to make payments and transfers in WeChat.

What does computer core mean? What does computer core mean? Sep 05, 2022 am 11:24 AM

Core has two meanings in computers: 1. The core, also known as the core, is the most important component of the CPU. All calculations, accepting storage commands, and processing data of the CPU are performed by the core; 2. Core, core is Intel's processor Name, Core is the processor brand launched by Intel after the Pentium processor. It has currently released twelfth generation Core processors.

How to implement editable tables in Vue How to implement editable tables in Vue Nov 08, 2023 pm 12:51 PM

Tables are an essential component in many web applications. Tables usually have large amounts of data, so tables require some specific features to improve user experience. One of the important features is editability. In this article, we will explore how to implement editable tables using Vue.js and provide specific code examples. Step 1: Prepare the data First, we need to prepare the data for the table. We can use a JSON object to store the table's data and store it in the data property of the Vue instance. In this case

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? How to bind a sub-account on Xiaohongshu? How does it check whether the account is normal? Mar 21, 2024 pm 10:11 PM

In today's era of information explosion, the construction of personal brand and corporate image has become increasingly important. As the leading fashion life sharing platform in China, Xiaohongshu has attracted a large number of user attention and participation. For those users who want to expand their influence and improve the efficiency of content dissemination, binding sub-accounts has become an effective means. So, how does Xiaohongshu bind a sub-account? How to check whether the account is normal? This article will answer these questions for you in detail. 1. How to bind a sub-account on Xiaohongshu? 1. Log in to your main account: First, you need to log in to your Xiaohongshu main account. 2. Open the settings menu: click &quot;Me&quot; in the upper right corner, and then select &quot;Settings&quot;. 3. Enter account management: In the settings menu, find the &quot;Account Management&quot; or &quot;Account Assistant&quot; option and click

Steps and methods to bind Douyin in Toutiao Steps and methods to bind Douyin in Toutiao Mar 22, 2024 pm 05:56 PM

1. Open Toutiao. 2. Click My in the lower right corner. 3. Click [System Settings]. 4. Click [Account and Privacy Settings]. 5. Click the button on the right side of [Douyin] to bind Douyin.

How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? How to bind the Cainiao app to Pinduoduo? How to add the Cainiao Wrap to Pinduoduo platform? Mar 19, 2024 pm 02:30 PM

The Cainiao app is a platform that can provide you with various logistics information. The functions here are very powerful and easy to use. If you have any logistics-related problems, they can be solved here. Anyway, it can bring you a The one-stop service can solve everything in time. Checking the express delivery, picking up the express delivery, sending the express delivery, etc. are all without any problems. We have cooperated with various platforms and all the information can be queried. However, sometimes It will happen that the goods purchased on Pinduoduo cannot display the logistics information. In fact, you need to manually bind Pinduoduo to achieve this. The specific methods have been sorted out below, and everyone can take a look. . How to bind Cainiao to Pinduoduo account: 1. Open Cainiao APP and go to the main page

See all articles