


Detailed explanation of the new features of ASP.NET Core 2.0 version
Amazing ASP.NET Core 2.0, this article mainly introduces the new features of ASP.NET Core 2.0 version. Interested friends can refer to it
Preface
ASP.NET Core changes and develops very 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 at Preview 1 Version means that the functions have been basically determined. Students who have not learned ASP.NET Core can start learning directly from 2.0, but if you have already mastered 1.0, then you only need to understand some of the functions added and modified in 2.0 That’s it.
Every major version release and upgrade will always bring some surprises and exciting features to developers. The new features of ASP.NET Core version 2.0 are mainly concentrated in several parts. superior.
Changes in SDK
PS: Currently, if you want to experience all the features of ASP.NET Core 2.0 in VS, you need the VS 2017.3 preview version. Of course you can use VS Core to get a quick understanding.
.NET Core 2.0 Priview download address:
www.microsoft.com/net/core/preview
After completion, you can use the following command in cmd to view the version.
Change 1: Added a new command as indicated by the arrow in the figure below.
dotnet new razor dotnet new nugetconfig dotnet new page dotnet new viewimports dotnet new viewstart
Added these new cli commands. Among them, viewimports and viewstart are the two files _xxx.cshtml in the Razor view.
Change 2: dotnet new xxx will automatically restore the NuGet package. There is no need for you to run the dotnet restore command again.
G:\Sample\ASPNETCore2 > dotnet new mvc The 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 2.0, when creating an MVC project, the generated csporj project file is as follows:
Among them, the red arrow part is the new content. Let’s take a look at it in turn:
MvcRazorCompileOnPublish:
In version 1.0, if we need to compile the Views folder in MVC into a DLL when publishing, we need to reference the
Microsoft.AspNetCore.Mvc.Razor.ViewCompilation NuGet package, which is now No need, this function has been integrated into the SDK by default. You only need to add configuration to csporj. When publishing, the *.cshtml file in the Views folder will be automatically packaged as 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 secrets used in the program. It used to be stored in the project.json file. Now you can Configuration is done here.
For more information about UserSecrets, you can check out this blog post of mine.
MVC related package
In Core MVC 2.0, all MVC-related NuGet packages are integrated into this Microsoft.AspNetCore.All package, which It is a metadata package that contains a lot of things, including: Authorization, Authentication, Identity, CORS, Localization, Logging, Razor, Kestrel, etc. In addition to these, it also adds EntityFramework, SqlServer, Sqlite, etc. Bag.
Some students may think that this will reference many assemblies that are not used in the project, causing the released program to become very large, but I want to tell you not to worry, the released assembly will not only be It will become larger, but much smaller, because Microsoft has integrated all these dependencies into the SDK, which means that after you install the SDK, the MVC related packages have already been installed on your system.
The advantage of this is that you don’t have to worry about hidden conflicts caused by a large number of version inconsistencies when updating or deleting Nuget packages. Another advantage is that it is very friendly to many novices. 2333 They don’t You need to know under what circumstances they will get the information they need from that NuGet package.
Now, the published folder is so concise: size 4.3M
Post the previous published file again Clip it for you to feel: size 16.5M
有些同学可能好奇他们把那些引用的 MVC 包放到哪里了,默认情况下他们位于这个目录:
C:\Program Files\dotnet\store\x64\netcoreapp2.0
新的 Program.cs 和 Startup.cs
现在,当创建一个 ASP.NET Core 2.0 MVC 程序的时候,Program 和 Startup 已经发生了变化,他们已经变成了这样:
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?}"); }); } }
可以发现,新的 Program.cs 中和 Startup.cs 中的内容已经变得很简单了,少了很多比如 appsetting.json 文件的添加,日志中间件, Kertrel , HostingEnvironment 等,那么是怎么回事呢? 其他他们已经被集成到了 WebHost.CreateDefaultBuilder 这个函数中,那么我们跟进源码来看一下内部是怎么做的。
WebHost.CreateDefaultBuilder
下面是 WebHost.CreateDefaultBuilder 这个函数的源码:
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; }
可看到,新的方式已经隐藏了很多细节,帮助我们完成了大部分的配置工作。但是你知道怎么样来自定义这些中间件或者配置也是必要的技能之一。
appsettings.json 的变化
在 appsettings.json 中,我们可以定义 Kestrel 相关的配置,应用程序会在启动的时候使用该配置进行Kerstrel的启动。
{ "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" } } }
以上配置内容配置了 Kertrel 启动的时候使用的本地地址和端口,以及在生产环境需要使用的 HTTPS 的配置项,通常情况下关于 HTTPS 的节点配置部分应该位于 appsettings.Production.json 文件中。
现在,dotnet run在启动的时候将同时监听 9000, 和 9001 端口。
日志的变化
在 ASP.NET Core 2.0 中关于日志的变化是非常令人欣慰的,因为它现在不是作为MVC中间件配置的一部分了,而是 Host 的一部分,这句话好像有点别扭,囧~。 这意味着你可以记录到更加底层产生的一些错误信息了。
现在你可以这样来扩展日志配置。
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(factory=>{你的配置}) .Build();
全新的 Razor Pages
ASP.NET Core 2.0 引入的另外一个令人兴奋的特性就是 Razor Pages。提供了另外一种方式可以让你在做Web 页面开发的时候更加的沉浸式编程,或者叫 page-focused 。额...它有点像以前 Web Form Page,它隶属于 MVC 框架的一部分,但是他们没有 Controller。
你可以通过dotnet new razor命令来新建一个 Razor Pages 类型的应用程序。
Razor Pages 的 cshtml 页面代码可能看起来是这样的:
@page @{ var message = "Hello, World!"; } <html> <body> <p>@message</p> </body> </html>
Razor Pages 的页面必须具有 @page 标记。他们可能还会有一个 *.cshtml.cs 的 class 文件,对应的页面相关的一些代码,是不是很像 Web Form 呢?
有同学可能会问了,没有 Controller 是怎么路由的呢? 实际上,他们是通过文件夹物理路径的方式进行导航,比如:
有关 Razor Pages的更多信息可以看这里:
docs.microsoft.com/en-us/aspnet/core/razor-pages
总结
可以看到,在 ASP.NET Core 2.0 中,给我们的开发过程带来了很多便利和帮助,他们包括 Program 等的改进,包括 MVC 相关 NuGet 包的集成,包括appsetting.json的服务器配置,以及令人惊讶的Razor Page,是不是已经迫不及待的期待正式版的发布呢?如果你期待的话,点个【推荐】让我知道吧~ 2333..
如果你对 ASP.NET Core 有兴趣的话可以关注我,我会定期的在博客分享我的学习心得。
【相关推荐】
3. 分享ASP.NET Core在开发环境中保存机密(User Secrets)的实例
4. .Net Core中如何使用ref和Span
The above is the detailed content of Detailed explanation of the new features of ASP.NET Core 2.0 version. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Microsoft's Windows 11 2022 Update (22H2) enables CoreIsolation's memory integrity protection by default. However, if you are running an older version of the operating system, such as Windows 11 2022 Update (22H1), you will need to turn this feature on manually. Turn on CoreIsolation's Memory Integrity feature in Windows 11 For users who don't know about Core Isolation, it's a security process designed to protect basic core activities on Windows from malicious programs by isolating them in memory. This process, combined with the memory integrity feature, ensures

Core has two meanings in computers: 1. The core, also known as the core, is the most important component of the CPU. All calculations, accepting storage commands, and processing data of the CPU are performed by the core; 2. Core, core is Intel's processor Name, Core is the processor brand launched by Intel after the Pentium processor. It has currently released twelfth generation Core processors.

Everyone knows that there are many versions of win7 system, such as win7 ultimate version, win7 professional version, win7 home version, etc. Many users are entangled between the home version and the ultimate version, and don’t know which version to choose, so today I will Let me tell you about the differences between Win7 Family Meal and Win7 Ultimate. Let’s take a look. 1. Experience Different Home Basic Edition makes your daily operations faster and simpler, and allows you to access your most frequently used programs and documents faster and more conveniently. Home Premium gives you the best entertainment experience, making it easy to enjoy and share your favorite TV shows, photos, videos, and music. The Ultimate Edition integrates all the functions of each edition and has all the entertainment functions and professional features of Windows 7 Home Premium.
![How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix]](https://img.php.cn/upload/article/000/000/164/168169038621890.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Most of the devices, such as laptops and desktops, have been heavily used by young gamers and coders for a long time. The system sometimes hangs due to application overload. This forces users to shut down their systems. This mainly happens to players who install and play heavy games. When the system tries to boot after force shutdown, it throws an error on a black screen as shown below: Below are the warnings detected during this boot. These can be viewed in the settings on the event log page. Warning: Processor thermal trip. Press any key to continue. ..These types of warning messages are always thrown when the processor temperature of a desktop or laptop exceeds its threshold temperature. Listed below are the reasons why this happens on Windows systems. Many heavy applications are in

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

With the rapid development of the Internet, programming languages are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

The three characteristics of 5g are: 1. High speed; in practical applications, the speed of 5G network is more than 10 times that of 4G network. 2. Low latency; the latency of 5G network is about tens of milliseconds, which is faster than human reaction speed. 3. Broad connection; the emergence of 5G network, combined with other technologies, will create a new scene of the Internet of Everything.
