mazing ASP. NET Core 2.0 "turn"

Source: Internet
Author: User
Tags dotnet webhost

The change and development speed of the ASP. NET core is fast, and when you find out that you haven't mastered ASP. 1.0, 2.0 is almost ready to release, now 2.0 is in Preview 1, which means that the functionality has been basically determined and has not yet learned the ASP. Ore students can start learning directly from 2.0, but if you have mastered 1.0, then you just need to know some of the features added and modified in 2.0.

The release and upgrade of each major release is always a surprise and exciting feature for developers, and the new features of the 2.0 version of the ASP. NET core are mainly focused on several parts.

Changes to the SDK

PS: Now if you want to experience all of the ASP. NET Core 2.0 features in VS, you need the VS 2017.3 preview version. Of course you can use VS Core to get a quick look.

. NET Core 2.0 Priview:
Https://www.microsoft.com/net/core/preview#windowscmd

You can use the following command to view the version in CMD when you are finished.

Change 1: Added a new command as indicated by the arrow.

new razordotnet new nugetconfigdotnet new pagedotnet new viewimportsdotnet new viewstart

These new CLI commands are added. Among them, that is viewimports , the viewstart razor view of the _xxx.cshtml that two files.

Change 2: dotnet new xxx The NuGet package will be automatically restored without you having to make the dotnet restore command again.

"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 2.0, when creating an MVC project, the resulting Csporj project file is as follows:

Where the Red Arrow section is new, let's look at it in turn:

mvcrazorcompileonpublish:

In version 1.0, if we need to compile the Views folder in MVC as a DLL at the time of publication, we need to reference
Microsoft.AspNetCore.Mvc.Razor.ViewCompilationThis NuGet package, and now no longer required, this feature has been integrated by default in the SDK, only need to add the configuration in Csporj, at the time of release will be automatically packaged in the Views folder *.cshtml file is the DLL assembly.

Packagetargetfallback

This configuration item is the target framework that is used to configure the current assembly support.

Usersecretsid

This is used to store the secret used in the program, previously stored in the project.json file, now you can configure it here.

For more information about usersecrets, you can view this blog post for me.

MVC-related Packages

Include="Microsoft.AspNetCore.All" Version="2.0.0-preview1-final" />

In Core MVC 2.0, all MVC-related nuget packages are integrated into this package, which Microsoft.AspNetCore.All is a metadata package that contains a large number of things, including: Authorization, authentication, Identity, CORS, Localization, Logging, Razor, Kestrel etc., in addition to these it also attaches entityframework, SQL Server, Sqlite and other packages.

Some students might think that this would refer to assemblies that are not used in many projects, resulting in a huge post-release program, but let me tell you not to worry that the post-release assemblies will not be large, but will be much smaller because Microsoft integrates all of these dependencies into the SDK. This means that when you install the SDK, the MVC-related packages are already installed on your system.

The advantage is that you don't have to worry about updating nuget packages or deleting them, because a lot of version inconsistencies cause hidden conflict issues, and another benefit is that it's nice for many novices to be 2333, they don't need to know what they're going to get from that NuGet Get the information you need in the package.

The post-publish folder is now so concise: size 4.3M

Post a previous post-release folder you can feel it: size 16.5M

Some students may wonder where they put the referenced MVC packages, by default they are in this directory:

C:\Program Files\dotnet\store\x64\netcoreapp2.0

The new Program.cs and Startup.cs

Now, when creating an ASP. NET Core 2.0 MVC, program and Startup have changed, and they have become:

Program.cs

PublicClassprogram{Public Static void Main(string[] args) { buildwebhost (args). run ();} public span class= "kw" >static Iwebhost buildwebhost  (string[] args) = Webhost.usestartup<startup> (). build ();}              

Startup.cs

PublicClassstartup{PublicStartup (IConfiguration configuration) {configuration = Configuration;}Public IConfiguration Configuration {get;} public void configureservices (iservicecollection services) {services. Addmvc (); } public void configure (iapplicationbuilder app, Ihostingenvironment env) { Span class= "Hljs-keyword" >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});}              

Can be found that the new Program.cs and Startup.cs in the content has become very simple, a lot less such as Appsetting.json file additions, log middleware, Kertrel, hostingenvironment, etc., So what's going on? Other they have been integrated into WebHost.CreateDefaultBuilder this function, then we follow the source to see how the internal is done.

Webhost.createdefaultbuilder

Here is the WebHost.CreateDefaultBuilder source code for this function:

Public StaticIwebhostbuilderCreatedefaultbuilder(String[] args) {var builder =NewWebhostbuilder ().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 (NewAssemblyName (env.ApplicationName));if (appassembly! =NULL) {config.Addusersecrets (appassembly, Optional:true); }} config.Addenvironmentvariables ();if (args! =NULL) {config.addcommandline (args); }) . configurelogging (hostingcontext, logging) = {Logging.getsection ( "Logging"); Logging.adddebug ();}) . useiisintegration (). usedefaultserviceprovider (context, options) = {Options.hostingenvironment. isdevelopment ();}) . configureservices (services = Services.return Builder;}         

As you can see, the new approach has hidden a lot of detail and helped us do most of the configuration work. But you know how to come from defining these middleware or configuration is also one of the necessary skills.

Changes in Appsettings.json

In Appsettings.json, we can define Kestrel-related configurations that the application uses to launch Kerstrel when it is started.

{"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" : < Span class= "hljs-literal" >false "loglevel" { "default"  "Warning" } }}   

The configuration above configures the local address and port used for Kertrel startup, as well as the configuration items for https that need to be used in the production environment, typically the node configuration section on HTTPS should be located in appsettings. The Production.json file.

Now, dotnet run at boot time, 9000, and 9001 ports will be monitored at the same time.

Changes to the log

The change in the log in ASP. NET Core 2.0 is very comforting, because it's not part of the MVC middleware configuration, it's part of the Host, which seems a bit awkward and embarrassing. This means that you can record some of the error messages that are generated at the bottom.

Now you can extend the log configuration as such.

  public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(factory=>{你的配置}) .Build();
The new Razor Pages

Another exciting feature introduced by ASP. Razor Pages. Provides another way to make your Web page development more immersive programming, or called page-focused. The amount ... It's a bit like the Web Form Page of the past, it's part of the MVC framework, but they don't have a Controller.

You can dotnet new razor create a new Razor Pages-type application by command.

The cshtml page code for Razor pages might look like this:

@page@{    var message = "Hello, World!";}<html><body> <p>@message</p></body></html>

Pages in Razor pages must have a @page tag. They may also have a *.cshtml.cs class file, corresponding to the page related to some code, is not much like Web Form it?

Some students may ask, no Controller is how to route it? In fact, they navigate through the physical path of a folder, such as:

file name and path Matching URLs
/pages/index.cshtml /Or/Index
/pages/contact.cshtml /Contact
/pages/store/contact.cshtml /Store/Contact

More information about Razor pages can be found here:
Https://docs.microsoft.com/en-us/aspnet/core/razor-pages

Summarize

As you can see, there is a lot of convenience and help in our development process in ASP. NET Core 2.0, including improvements to the program, including the integration of MVC-related NuGet packages, including Appsetting.json server configuration, and surprisingly razor Page, is not eager to look forward to the release of the official version of it? If you're looking forward to it, "recommend" Let me know ~ 2333.

If you are interested in ASP. You can pay attention to me, I will regularly share my learning experience on the blog.

This address: http://www.cnblogs.com/savorboard/p/aspnetcore2-feature.html
Author Blog: Savorboard
Welcome reprint, please give the source and link in obvious position

mazing ASP. NET Core 2.0 "turn"

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.