Home > Backend Development > C#.Net Tutorial > Detailed explanation of the new features of ASP.NET Core 2.0 version

Detailed explanation of the new features of ASP.NET Core 2.0 version

零下一度
Release: 2018-05-24 13:55:17
Original
6399 people have browsed it

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
Copy after login

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.
Copy after login

*.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

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.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();
}
Copy after login

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?}");
 });
 }
}
Copy after login

可以发现,新的 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;
}
Copy after login

可看到,新的方式已经隐藏了很多细节,帮助我们完成了大部分的配置工作。但是你知道怎么样来自定义这些中间件或者配置也是必要的技能之一。

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"
 }
 }
}
Copy after login

以上配置内容配置了 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();
Copy after login

全新的 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>
Copy after login

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 有兴趣的话可以关注我,我会定期的在博客分享我的学习心得。

【相关推荐】

1. ASP.NET免费视频教程

2. 详细介绍ASP.NET MVC--路由

3. 分享ASP.NET Core在开发环境中保存机密(User Secrets)的实例

4. .Net Core中如何使用ref和Span提高程序性能的实现代码

5. Core实现全面扫盲贴的ASP方法详解

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template