search
HomeBackend DevelopmentC#.Net TutorialDetailed 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

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();
}

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

【相关推荐】

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!

Statement
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
C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft