Categories
Uncategorized

[ASP.NET Core 3 framework Secret] cross-platform development experience: Windows [novellas]

We created a simple console program in the “Part” use dotnet new command, then we will transform it into a ASP.NET Core applications. A ASP.NET Core ASP.NET Core application built on top of the frame, the frame ASP.NET Core using a message processing pipeline completed listens to the HTTP request, receiving, processing and final response. ASP.NET Core pipe consists of a server (Server), and a plurality of intermediate (the Middleware), after the host (the Host) starts, is constructed out of the pipe, as the pipe “leading” start listening for HTTP server from the client.

First, add a reference

Next we open directly in front of the helloworld.csproj Visual Studio project file. To be able to use the Assembly ASP.NET Core framework, we can add the framework for “Microsoft.AspNetCore.App” references (FrameworkReference) by modifying the project file (.csproj). Modify the project file in Visual Studio is very easy, we only need to select the right target item, and select “Edit Project File” from the pop-up menu on it. The following items are modified file, for frame “Microsoft.AspNetCore.App” is added to the reference next node.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>ExeOutputType>
    <TargetFramework>netcoreapp3.0TargetFramework>
  PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App"/>
  ItemGroup>
Project>

Second, the registration server and middleware

Carrier or from the application host (Hosting) terms, .NET Core having one to IHost / IHostBuilder bearer service system as the core, any long-running operations can be defined as IHostedService and services carried by the system. IHost all objects may be considered a host (the Host) bearer service, and it is an object IHostBuilder builder (Builder). A ASP.NET Core application is essentially a monitor to receive and process the HTTP request back-office services, so it is defined as a GenericWebHostService (IHostedService implements the interface), we will register it in turn to carry the system achieved for ASP .NET Core bearing applications.

A running ASP.NET Core essentially reflected by the application server and a message processing pipeline consisting of several middleware server listens for HTTP requests solution, and receiving the final response, specific to processing the request by submitting it to a subsequent middleware to complete. The pipeline was built by GenericWebHostService out of service previously mentioned.

ASP.NET Core Services provides several types of native, more commonly used it is KestrelServer and HTTP.sys. KestrelServer is a cross-platform Web server, can be used on Windows, Mac OS and Linux. It not only can be used as stand-alone Web server directly provide services, can also be combined with traditional Web server (such as IIS, Apache and NGinx) and use them as a reverse proxy to use. HTTP.sys is only a Windows Web server platform, since it is essentially a driver in the operating system kernel mode, it can provide very good performance.

After the above changes were made to the project file helloworld.csproj, we made the following definition of the transformation of the Main method in Program.cs. We call CreateDefaultBuilder method Static type Host creates a IHostBuilder object and end up calling the object method Build constructed as a service hosted IHost object. When we call IHost object Run time extension methods, ASP.NET Core application will be launched.

Before building Build IHost object calls a method, a method we call the extension ConfigureWebHost IHostBuilder interface, and using the specified Action constructed delegate object request processing pipeline ASP.NET Core applications. Specifically, we call UseKestrel extension methods IWebHostBuilder interface will KestrelServer registered as a server, call the extension method Configure registered middleware to handle the request. Configure input parameter is a method Action objects, required in the intermediate register IApplicationBuilder object. The only middleware demo registration is registered by the Run method invocation IApplicationBuilder expansion interface, the middleware using the specified Func object body content of the response to “Hello World”.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;

namespace helloworld
{
    class Program
    {
        static void Main()
        {
            Host.CreateDefaultBuilder()
                .ConfigureWebHost(webHostBuilder => webHostBuilder
                    .UseKestrel()
                    .Configure(app => app.Run(
                         context => context.Response.WriteAsync("Hello World."))))
                .Build()
                .Run();
        }
    }
}

We can follow the above presentation as to start the program by executing dotnet command line, you can also start the program by pressing F5 or Ctrl + F5 directly in Visual Studio. It is shown below the output result after executing the command console dotnet run, in fact, these outputs are outputted in the form of logs. We can see that the default listen address used by ASP.NET Core applications from these outputs (http // localhost: 5000 and https // localhost: 5001) and hosting environment (Production). If you need to close the application, simply press Ctrl + C key combination on it.

Registered KestrelServer server will bind to http // localhost: 5000 and https // localhost: 5001 address both listening for requests, if we are using a browser to initiate a request to both addresses will be what kind of response it? As shown below, two requests will get the main content is “Hello World.” The response (due to the issue of the certificate, Chrome browser displays “Not secure” a warning to the HTTPS requests), there is no doubt that content is what we registration middleware written.

Third, modify SDK

Each .NET Core applications for a particular type of SDK. Earlier, we showed a complete definition of project files helloworld.csproj, which is an XML file on the root node set the current project type SDK SDK used by property. For the previous command by dotnet new tool created out of the console application, it uses the default SDK type is “Microsoft.NET.Sdk”. For an ASP.NET Core application, we generally will use another type called “Microsoft.NET.Sdk.Web” of the SDK.

If the SDK is set to “Microsoft.NET.Sdk.Web”, we can even delete the references from the project file for the frame “Microsoft.AspNetCore.App” of. Since we do not need to use the .exe file to start the ASP.NET Core generated application, so we should be XML element Exe Delete from node, so the final project file to keep only the following contents on it.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0TargetFramework>
  PropertyGroup>
Project>

Four, launchSettings.json

When we modify the project file helloworld.csproj SDK will be changed to “Microsoft.NET.Sdk.Web”, if we use Visual Studio to open this file, named “launchSettings.json” configuration file is automatically generated and saved under “\ Properties” directory. As the name suggests, launchSettings.json is automatically loads a configuration file when the application starts up, the configuration file so that we can execute our application in different settings. LaunchSettings.json is the content of the file Visual Studio automatically created as shown below. We can see that the default configuration file adds two nodes, where “iisSettings” option is set for IIS-related, and “profiles” for representing node defines a set of application startup scene Profile.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51127/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "helloworld": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:51128/"
    }
  }
}

The initial launchSettings.json two files are created by default Profile, a named “IIS Express”, another is used to name the current project ( “helloworld”). Each Profile is equivalent to define the scene to start the application, including applications startup settings related to the way the environment variables and URL, the specific settings include:

    commandName: Start a command type of the current application, available options include IIS, IISExpress, Executable and Project, the first three options are represented using IIS, IISExpress and specified executable file (.exe) to start the application. If we use dotnet run command to start the program, the corresponding Profile start naming names should be set for the Project.

    executablePath: If commandName property is set to Executable, we need to use this property to set the path (absolute or relative path) to start the executable file.

    environmentVariables: This attribute is used to set the environment variables. Since launchSettings.json used only in a development environment, so the default will add a file called “ASPNETCORE_ENVIRONMENT” environment variable, and its value is set to “Development”, ASP.NET Core applications is the use of an environment variable to indicate the current the deployment environment.

    commandLineArgs: command-line parameters, namely the list of parameters passed in the Main method.

    workingDirectory: Start the current application running working directory.

    applicationUrl: URL list application used, among a plurality of URL using semicolons ( ‘;’) separated.

    launchBrowser: a Boolean switch, indicates that the application time whether to activate the browser automatically.

    launchUrl: If launchBrowser is set to true, the browser uses the initialization path is set via the attribute.

    nativeDebugging: whether to start the native code debugging (Native Code Debugging), the default value is false.

    externalUrlConfiguration: If the property is set to true, means that disable local configuration, the default value is false.

    use64Bit: If the property is set to commandName IIS Express, is the use of the property decided to X64 or X86 version version, the default value is false, meaning ASP.NET Core X86 application will use the default version of IIS Express.

All settings launchSettings.json file only for the development environment, production environment does not require this document, a list of files generated after application release does not contain the file. The files do not need to manually edit the current Project Properties dialog box (right click and select “Properties (Properties)” option in the dialog box solutions) in the “Debug (Debug)” all settings under the tab will be reflected in the final on the file.

If multiple Profile in launchSettings.json file, they will form shown below appears in the Visual Studio toolbar, we can choose any one defined in the Profile configuration options to start the current application. If you start the browser, select the Profile by setting launchBrowser property, we can also choose the type of browser.

If we start the application by executing dotnet run commands in the current directory project, launchSettings.json file will be loaded by default. We can command line parameters Profile –launch-profile designated uses. If you do not make an explicit designation Profile, defined in the configuration file for the first commandName “Project” The Profile will be used by default. As shown below, we initiated our application dotnet run by executing the command in the application of the root directory is created, wherein the first time through the dotnet run command explicitly set Profile Name (–launch-profile helloworld). From the results outputted twice it uses the same Profile.

If the time in the implementation of dotnet run command does not want to load launchSettings.json file, we can be done by explicitly specifying the command line argument –no-launch-profile. As shown below, we perform a dotnet run command specifies the –no-launch-profile parameters, the application will use KestrelServer default listen address (http: // localhost: 5000 and https: // localhost: 5001). Since launchSettings.json simply not be loaded, so the current execution environment into a default from the Development of Production.

V. explicitly specified URL

If you do not want to use the URL launchSettings.json defined in the file, you do not want to use the default listen address KestrelServer adopted, we can explicitly specify the URL of the application in the application. As shown in the code segment below, we only need to call the extension method IWebHostBuilder UseUrls URL to specify a set separated by semicolons.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder()
            .ConfigureWebHost(webHostBuilder => webHostBuilder
                .UseKestrel()
                .UseUrls("http://0.0.0.0:3721;https://0.0.0.0:9527")
                .Configure(app => app.Run(context => context.Response.WriteAsync("Hello World."))))
            .Build()
            .Run();
    }
}

Six, ConfigureWebHostDefaults

ConfigureWebHost extension method demonstrated above example, we are calling IHostBuilder interface specified by Action delegate object to construct a processing request processing pipeline, there is another interface ConfigureWebHostDefaults extension method, which will make some of us default setting. As shown in the following code fragment, if this method is invoked, KestrelServer servers do not need to be explicit registration.

class Program
{
    static void Main()
    {
        Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.Configure(app => app.Run(context => context.Response.WriteAsync("Hello World."))))
            .Build()
            .Run();
    }
}

[ASP.NET Core 3 framework Secret] cross-platform development experience: Windows [Part] [ASP.NET Core 3 framework Secret] cross-platform development experience: Windows [novellas] [ASP.NET Core 3 framework Secret] cross-platform development experience: Windows [next] [ASP.NET Core 3 framework Secret] cross-platform development experience: Mac OS [ASP.NET Core 3 framework Secret] cross-platform development experience: Linux [ASP.NET Core 3 framework Secret] cross-platform development experience: Docker

Leave a Reply