Amazing ASP. NET Core 2.0, amazingcore
Preface
ASP. NET Core changes and development speed are fast, when you find that you have not mastered ASP. NET Core 1.0, 2.0 is about to be released. Currently, 2.0 is in Preview 1, which means the function has been basically determined and ASP has not been learned yet. NET Core users can start learning from 2.0, but if you have mastered 1.0, you only need to know some of the functions added and modified in 2.0.
Every major version release and upgrade will always surprise developers and exciting features related to ASP. the new features of NET Core 2.0 are mainly concentrated in several parts.
SDK changes
PS: If you want to experience all ASP. NET Core 2.0 features in VS, You need to preview VS 2017.3. Of course, you can use VS Core for quick understanding.
. NET Core 2.0 Priview:
Https://www.microsoft.com/net/core/preview
Run the following command in cmd to view the version.
Change 1:Added a new command as indicated by the arrow.
dotnet new razordotnet new nugetconfigdotnet new pagedotnet new viewimportsdotnet new viewstart
Added these new cli commands. Here, viewimports and viewstart are the _ xxx. cshtml files in the Razor view.
Change 2:Dotnet new xxx will automatically restore the NuGet package. You do not need to run the dotnet restore command again.
G:\Sample\ASPNETCore2 > dotnet new mvcThe template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.Processing post-creation actions...Running 'dotnet restore' on G:\Sample\ASPNETCore2\ASPNETCore2.csproj...Restore succeeded.
*. Csproj project file
In section 2.0, when creating an MVC project, the csporj project file generated is as follows:
The red arrow shows the newly added content. Let's take a look at it one by one:
MvcRazorCompileOnPublish:
In Version 1.0, if we need to compile the Views folder in MVC as DLL during release, we need to reference
Microsoft. aspNetCore. mvc. razor. viewCompilation, The NuGet package, is no longer needed. This feature is already integrated into the SDK by default. You only need to add the configuration in csporj, the *. the cshtml file is a DLL assembly.
PackageTargetFallback
This configuration item is used to configure the target framework supported by the current Assembly.
UserSecretsId
This is used to store the secret used in the program. It was previously stored in the project. json file. Now you can configure it here.
For more information about UserSecrets, see my blog post.
MVC packages
<PackageReference Include = "Microsoft. AspNetCore. All" Version = "2.0.0-preview1-final"/>
In Core MVC 2.0, all MVC-related NuGet packages are integrated into this Microsoft. aspNetCore. in the All package, it is a metadata package that contains a large number of things, including Authorization, Authentication, Identity, CORS, Localization, Logging, Razor, Kestrel, etc, in addition, it also attaches the EntityFramework, SqlServer, Sqlite and other packages.
Some may think that this will reference the assembly that is not used in many projects, resulting in a huge number of released programs, but I want to tell you not to worry, after the release, the Assembly will not become very large, but will be much smaller, because Microsoft integrates all these dependencies into the sdk, that is, after you install the sdk, the MVC-related packages have been installed on your system.
The advantage is that you do not have to worry about updating or deleting the Nuget package. A large number of version inconsistencies may cause hidden conflicts. Another benefit is that, in this way, many new users will be very friendly. They do not need to know what information they need from the NuGet package.
Now,The released folder is so concise: The size is 4.3 MB.
Paste a previously released folder. You can feel it: the size is 16.5 MB.
Some may wonder where they put the referenced MVC packages. By default, they are located in this directory:
C: \ Program Files \ dotnet \ store \ x64 \ netcoreapp2.0
New Program. cs and Startup. cs
Now, when you create an ASP. NET Core 2.0 MVC Program, Program and Startup have changed, and they have changed to the following:
Program. cs
public class Program{ public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build();}
Startup. cs
public class Startup{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }}
We can find that the new Program. cs and Startup. the content in cs has become very simple, and a lot less, such as deleetting. how does one add json files, Log Middleware, Kertrel, and HostingEnvironment? The other functions have been integrated into the WebHost. createdefabuilder builder function, so let's follow up the source code to see how it is implemented internally.
WebHost. createdefabuilder Builder
The following is the source code of the WebHost. createdefabuilder builder function:
public static IWebHostBuilder CreateDefaultBuilder(string[] args){ var builder = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); if (env.IsDevelopment()) { var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName)); if (appAssembly != null) { config.AddUserSecrets(appAssembly, optional: true); } } config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureLogging((hostingContext, logging) => { logging.UseConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); }) .UseIISIntegration() .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .ConfigureServices(services => { services.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>(); }); return builder;}
We can see that the new method has hidden many details and helped us complete most of the configuration work. But you know how to customize these middleware or configurations is also one of the necessary skills.
Appsettings. json changes
In appsettings. json, we can define the Kestrel-related configuration. The application will use this configuration to start Kerstrel at startup.
{ "Kestrel": { "Endpoints": { "Localhost": { "Address": "127.0.0.1", "Port": "9000" }, "LocalhostHttps": { "Address": "127.0.0.1", "Port": "9001", "Certificate": "Https" } } }, "Certificate": { "HTTPS": { "Source": "Store", "StoreLocation": "LocalMachine", "StoreName": "MyName", "Subject": "CN=localhost", "AllowInvalid": true } }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }}
The configuration above configures the local address and port used when Kertrel is started, as well as the HTTPS configuration items to be used in the production environment. Generally, the configuration of the HTTPS node should be located in appsettings. production. json file.
Now, dotnet run listens to ports 9000 and 9001 at startup.
Log Changes
In ASP. NET Core 2.0 is very pleased with the Log changes, because it is not a part of the MVC middleware configuration, but a part of the Host, it seems a bit awkward, region ~. This means that you can record some error messages generated at the underlying layer.
Now you can extend the log configuration.
Public static IWebHost BuildWebHost (string [] args) => WebHost. createdefabuilder Builder (args ). useStartup <Startup> (). configureLogging (factory =>{ your configuration }). build ();
New Razor Pages
Another exciting feature introduced in ASP. NET Core 2.0 is Razor Pages. Another method is provided to enable you to immerse yourself in Web page development, or call it page-focused. It's a bit like Web Form Page, which is part of the MVC framework, but they don't have a Controller.
You can use the dotnet new razor command to create a Razor Pages application.
The cshtml Page code of Razor Pages may look like this:
@page@{ var message = "Hello, World!";}
The Razor Pages page must have the @ page mark. They may also have a class file *. cshtml. cs, corresponding to some page-related code, isn't it like a Web Form?
Some may ask, how does one route without a Controller? In fact, they navigate through the folder physical path, such:
For more information about Razor Pages, see here:
Https://docs.microsoft.com/en-us/aspnet/core/razor-pages
Summary
You can see that in ASP. NET Core 2.0 brings a lot of convenience and help to our development process, including Program and other improvements, including integration of MVC-related NuGet packages, including deleetting. is the server configuration of json and the surprising Razor Page ready to be released in the official version? If you are looking forward to it, click [recommendation] to let me know ~ 2333 ..
If you are interested in ASP. NET Core, you can follow me. I will share my learning experience on a regular blog.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.