ASP. NET core Source series (i)

Source: Internet
Author: User
Tags hosting webhost

Objective

ASP. One months, I am working after-school time to read its source code, will be a series of understanding and ideas recorded, but also hope to get the garden peer guidance, common progress, here is just my understanding of the source code, there is the wrong place, I hope you correct, This is going to be a series of articles.

Entrance

After you create an ASP. NET Core project, you can see a Program.cs and a Startup.cs, and today I'll focus on what Program.cs has done,

 Public Static void Main (string[] args)        {            varnew  webhostbuilder ()                . Usekestrel ()                . Usecontentroot (Directory.GetCurrentDirectory ())                . Useiisintegration ()                . Usestartup<Startup>()                . Build ();            Host. Run ();        }
View Code

Here the Main method is the entry of the application does not have to say, you can see the entrance to create a Webhostbuilder instance object, and then a series of configuration for him, the last execution of the build method to return an instance of a Iwebhost object, and finally execute his run, method, At this point, the application starts up, so what exactly does this series of configurations do, we need to look at the Webhost class, and we go to GitHub to download the source code and look at it slowly. Link is aspnet/hosting, download down can be opened directly with VS2015 Update3. First we have to look at the Webhostbuilder class.

Webhostbuilder

An instance of this class is prepared to create a class instance of webhost, so let's look at how he constructs it:

 PublicWebhostbuilder () {_hostingenvironment=Newhostingenvironment (); _configureservicesdelegates=NewList<action<iservicecollection>>(); _configureloggingdelegates=NewList<action<iloggerfactory>>(); _config=NewConfigurationbuilder (). Addenvironmentvariables (prefix:"aspnetcore_")                .            Build (); if(string. IsNullOrEmpty (GetSetting (Webhostdefaults.environmentkey))) {//Try Adding legacy environment keys, never remove these.Usesetting (Webhostdefaults.environmentkey, Environment.getenvironmentvariable ("hosting:environment")                     ?? Environment.getenvironmentvariable ("aspnet_env")); }            if(string. IsNullOrEmpty (GetSetting (Webhostdefaults.serverurlskey))) {//Try adding Legacy URL key, never remove this.Usesetting (Webhostdefaults.serverurlskey, Environment.getenvironmentvariable ("Aspnetcore_server. URLS")); }        }
View Code

This method initializes some basic variables, _hostingenvironment (host environment configuration, including environment name, application name, Webroot path, Contentroot path), _ Configureservicesdelegates (in the name of a delegate collection of service operations), _configureloggingdelegates (a delegate collection of log operations from the name), _config (an instance of the configuration creator), Then two configurations ("Environment" and "URLs") are written to the _config.

Then call the extension method Usekestrel (), and let's look at the code:

   Public Static Iwebhostbuilder Usekestrel ( this iwebhostbuilder hostbuilder)    {      return Hostbuilder.configureservices ((action<iservicecollection>) (services =        Servicecollectionserviceextensions.addtransient<iconfigureoptions<kestrelserveroptions> Kestrelserveroptionssetup>(services);        Servicecollectionserviceextensions.addsingleton<iserver, kestrelserver>(services);      });    }
View Code

This method calls Webhostbuilder's Configureservices method to add some of the delegate handling methods of the kestrel to host, mainly including adding kestrel and some of its configuration options to the application's service processing collection.

Then call the Usecontentroot (Directory.GetCurrentDirectory ()) method and let's look at the code:

 Public Static Iwebhostbuilder Usecontentroot (Thisstring  contentroot)    {      ifnull  )        thrownew ArgumentNullException ("contentroot " );       return hostbuilder.usesetting (Webhostdefaults.contentrootkey, contentroot);    }
View Code

This extension method still calls the Useseeting () method to add the configuration item "Contentroot" (The content directory of the application, see link) to the _config configuration, and the value is the current directory.

Then call Useiisintegration () This extension method, let's look at the code:

 Public StaticIwebhostbuilder Useiisintegration ( ThisIwebhostbuilder app) {      if(App = =NULL)        Throw NewArgumentNullException ("app"); stringSTR1 = App. GetSetting (webhostbuilderiisextensions.serverport)?? Environment.getenvironmentvariable (string. Format ("aspnetcore_{0}", (Object) (Webhostbuilderiisextensions.serverport)) ; stringstr2 = App. GetSetting (Webhostbuilderiisextensions.serverpath)?? Environment.getenvironmentvariable (string. Format ("aspnetcore_{0}", (Object) (Webhostbuilderiisextensions.serverpath)) ; stringPairingtoken = App. GetSetting (Webhostbuilderiisextensions.pairingtoken)?? Environment.getenvironmentvariable (string. Format ("aspnetcore_{0}", (Object) (Webhostbuilderiisextensions.pairingtoken)) ; if(!string. IsNullOrEmpty (STR1) &&!string. IsNullOrEmpty (STR2) &&!string. IsNullOrEmpty (Pairingtoken)) {stringSTR3 ="http://localhost:"+ str1 +str2; App.        Usesetting (Webhostdefaults.serverurlskey, STR3); Hostingabstractionswebhostbuilderextensions.capturestartuperrors (app,true); App. Configureservices (Action<IServiceCollection>) (Services ={Servicecollectionserviceextensions.addsingleton<IStartupFilter> (Services, (Istartupfilter)NewIissetupfilter (Pairingtoken)); Optionsservicecollectionextensions.configure<ForwardedHeadersOptions> (Services, (action<forwardedheadersoptions>) (options ={options. Forwardedheaders= Forwardedheaders.xforwardedfor |Forwardedheaders.xforwardedproto; BOOLFlag =!string. IsNullOrEmpty (Environment.getenvironmentvariable ("website_instance_id")); Options. Requireheadersymmetry= !Flag;        }));      })); }      returnapp; }
View Code

Here is mainly the configuration of IIS, my understanding is that IIS will listen to the request to the kestrel to do processing, so the real monitoring or IIS, of course, this step can also be omitted directly, there is a direct kestrel to listen to the port request. Comment out the call to this method, launch the application directly to access localhost:5000 as you can (you can try it).

Next is the Usestartup<startup> () method, this method and the Startup class, I will do a separate explanation in the next article, mainly to set up the ASPNET core processing module (we are the MVC processing)

Finally, the Builder () method:

 Publiciwebhost Build () {//Warn about deprecated environment variables            if(Environment.getenvironmentvariable ("hosting:environment") !=NULL) {Console.WriteLine ("The environment variable ' hosting:environment ' is obsolete and have been replaced with ' aspnetcore_environment '"); }            if(Environment.getenvironmentvariable ("aspnet_env") !=NULL) {Console.WriteLine ("The environment variable ' aspnet_env ' is obsolete and have been replaced with ' aspnetcore_environment '"); }            if(Environment.getenvironmentvariable ("Aspnetcore_server. URLS") !=NULL) {Console.WriteLine ("The environment variable ' aspnetcore_server. URLS ' is obsolete and have been replaced with ' Aspnetcore_urls '"); }            varHostingservices =buildhostingservices (); varHostingcontainer =Hostingservices.buildserviceprovider (); varHost =Newwebhost (hostingservices, Hostingcontainer, _options, _config); Host.            Initialize (); returnhost; }
View Code

This method generates a final host for an application based on a previously registered set of services (listening service, log service, and so on) and configuration, and initializes him (both the invocation and the creation method source code are clear).

Then call the Host.run () method to start the service, and the specific invocation of the Run method will be analyzed in a separate chapter.

Summarize

This article just to create a host object to do some system description, the concrete implementation of a lot of really many, some I have not seen, feel that every method has a lot of things, I will slowly improve, there is a misunderstanding of the place, I hope you point out. We hope that the ecological circle of. NET is getting better and more and we work together. Recommend a link to a website

There is an online discussion about the ASPNET.

If you feel that it is helpful to you, please recommend it.

ASP. NET core Source series (i)

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.