Typically, we use hard-coded methods in Prgram.cs to configure the Hosting environment for an ASP. NET Core site, which is most commonly used. Useurls ().
public class program{ static void Main (string [] (args) { var host = new Webhostbuilder () . Useurls ( " http://* : style= "color: #800000;" " ) . Usekestrel (). Usecontentroot (Directory.GetCurrentDirectory ()). Usestartup <startup> (). Build (); Host. Run (); }}
But this hard-coded way to bind ports can cause trouble deploying multiple sites on the same Linux server because different sites need to bind different ports. Unless you have agreed on the ports used by each project at development time, it is easy to run into port conflict issues during deployment, forcing you to modify the code.
If you can set the bound port through the configuration file, this problem will be solved. Does ASP. NET Core provide a corresponding solution? With this problem, check out the source of aspnet/hosting today, in the samplestartups StartupFullControl.cs found the answer:
var New Configurationbuilder () . Addcommandline (args) "aspnetcore_") . Addjsonfile ("hosting.json"true) . Build (); var New Webhostbuilder () . Useconfiguration (config)
The original can be configured through Hosting.json, the following actual experience.
First create a Hosting.json file:
{ "server.urls": "http://*:5000;http://*:8001", "Environment": "Development"}
In addition to configuring Server.urls in the above configuration, the environment (default is production) is also configured.
Then use the configuration in the Program.cs in the Hosting.json:
Public classprogram{ Public Static voidMain (string[] args) { varConfig =NewConfigurationbuilder (). Addjsonfile ("Hosting.json", Optional:true) . Build (); varHost =NewWebhostbuilder () . Useurls ( "http://*:5000" ) . Usekestrel (). Usecontentroot (Directory.GetCurrentDirectory ()). Usestartup<Startup>() . Useconfiguration (config) . Build (); Host. Run (); }}
Attention must be put on the above. Useurls () is removed, otherwise the configuration in the Hosting.json will be overwritten by it.
Also note that in Project.json, in addition to adding "Hosting.json" in "Publishoptions", also add "Copytooutput" in "Buildoptions", "Hosting.json" ", otherwise the Hosting.json file will not be found in the Bin folder at run time.
"Buildoptions": { "Emitentrypoint": True, "Preservecompilationcontext": True, "copytooutput": " Hosting.json "}," Publishoptions ": { " include ": [ " Hosting.json " ]}
Finally, run the site with the dotnet Run command to experience the actual effect.
Hosting environment:developmentcontent root Path:c:\dev\cnblogs.webdemonow listening On:http://*:5000now listening on : Http://*:8001application started. Press CTRL + C to shut down.
Configuring the hosting environment for an ASP. NET Core site with "Hosting.json"