ASP.NET Core: The new ASP.NET!

background

The latest version of ASP.NET is called ASP.NET Core (also known as ASP.NET 5) and it turns the old ASP.NET upside down.

What is ASP.NET Core?

ASP.NET Core 1.0  is an open source, cross-platform development framework for building modern cloud-based web applications. It is rebuilt from the bottom to provide a web application development framework with excellent performance, which can be deployed on the cloud or on a local server. In addition, it makes ASP.NET applications more compact and modular (you can add other modules according to your application needs), cross-platform (you can easily develop and deploy your application on Windows, Mac or Linux), Cloud optimization (where you can deploy and debug your app on the cloud).

previous version

What does this mean for us using older versions of ASP.NET?

If you're using an older version of ASP.NET or you have a WebForms development background, then you'll realize how perfect ASP.NET Core is, it feels like it's coming from the old ASP days to the new ASP.NET world.

1

Now, let's find out

The core changes in ASP.NET Core 1.0 are listed below.

cross-platform runtime

You can run ASP.NET Core applications on OSX and Linux, which has cross-generational significance for ASP.NET and brings a new experience to ASP.NET developers and designers. ASP.NET Core has two runtimes, which means you can choose different runtime environments to deploy your application, making your application more flexible.

ASP.NET Core 1.0  is a refactored version of ASP.NET that runs on the latest .NET Core. It is modular, allowing developers to add modules needed by the application in the form of plugins, and most of the functionality will be provided as plugins and managed through NuGet packages. One advantage of this is that you can upgrade one module of the application without affecting other modules in the slightest; in addition, .NET Core is a cross-platform runtime, so you can deploy your application on OSX or Linux operating systems; It is also a cloud-optimized runtime for deploying and debugging applications on the cloud; .NET Core can be deployed alongside your application, and you can still run ASP.NET when there are multiple .NET Core versions on the server. NET Core application.

You can also create ASP.NET Core applications that only run the full .NET framework under Windows.

ASP.NET 4.6 is the latest release of the full .NET Framework, which allows you to take advantage of all .NET components and is backward compatible. If you plan to migrate your application to .NET core, you will need to make moderate changes because .NET Core has limitations relative to the full .NET Framework.

To be clear, ASP.NET 4.6 is more mature. It is now tried and tested and is now released and available. ASP.NET Core 1.0 is a 1.0 release that includes Web API and MVC, but no SignalR and Web Pages yet. , it also does not support VB and F# languages.

ASP.NET Core no longer relies solely on Visual Studio

The cross-platform nature of ASP.NET Core  makes it no longer dependent on Visual Studio, so developers and designers can work in their preferred environment. Like Sublime Text, WebStorm, it's awesome!

New Engineering Solutions Structure

如果你使用 Visual Studio 创建了一个空的 ASP.NET Core 工程,那么你将会看到下面的惊喜。(除非你没有使用之前的 ASP.NET 创建过任何项目)

2

你感觉到惊喜了吗?新的工程结构完全不一样了, 工程模板焕然一新,包含以下的新文件:

· global.json: 你可以在这里放置解决方案的配置信息和工程之间的引用。

· Program.cs: 这个文件包含了 ASP.NET Core RC2 应用的 Main 方法,负责配置和启动应用程序。

· src folder: 包含组成你应用程序的全部项目代码。

· wwwroot: 你的静态文件将被放置在这个文件夹,它们都将作为资源直接提供给客户端,包含 HTML,CSS 和 JavaScript 文件。

· project.json: 包含项目设置。在 ASP.NET Core中,你可以通过使用 NuGet 程序包管理工具(NPM)添加 NuGet 包或者编辑这个文件来管理从属。你可以通过任何文本编辑器来编辑这个文件,如果你使用 Visual Studio 2015,,这将会更加 轻松,因为它的智能提示会帮助你找到合适的 NuGet 包作为从属。project.json 就像下面这样。

3

· startup.cs 这个主要放置你 ASP.NET Core 的 stratup 和 configuration 代码,下面就是 stratup 类的样子。

4

ConfigureServices 方法定义了你应用程序使用的服务,Configure 方法用来定义组成请求管道的中间件。

· References: 它包含了 .NETCoreApp 第一个版本运行时的引用。

WebForms

是的,WebForms 不再是 ASP.NET 5 的一部分,这真令人悲伤。你可以继续使用 VS2015 的 .NET 4.6 来构建 Web Forms 应用,但是却不能体会 ASP.NET 5 的新特性了。

我已经开发了很多年从小型到大型的企业级 Web Forms 应用。 我很喜欢 Web Forms,,事实上我还会继续支持在各种论坛使用 WebForms 的社区,比如 http://forums.asp.net。但是我们是时候进步了,去学习一些新东西。这是学习 ASP.NET MVC 最后的时间了,就像过去的许多事物,你要么去适应,要么被淘汰。

除了 WebForms, the .NET Core 也没有包含 Windows Forms, WCF, WPF, Silverlight 等等。

VB.NET and F#

目前,在当前 ASP.NET Core 1.0 RC2 版本中, VB.NET 和 F# 也不被支持。

MVC Core 统一架构

5

 

ASP.NET Core 将见证 MVC, Web API 和 Web Pages(可能包含)组合在一个架构中,它被称为 ASP.NET MVC Core。尽管当前发布版本中,还不支持 Web Pages and SignalR。

在之前的 ASP.NET MVC 中, MVC 控制器和 Web API 控制器是不同的。 一个 MVC 控制器使用基类 System.Web.MVC.Controller ,一个 Web API 控制器使用基类 System.Web.Http.ApiController 。 在 MVC Core 中,会为它们提供一个共同的基类,就是 Microsoft.AspNetCore.Mvc.Controller 。

对于 HTML Helpers 来说,MVC 和 Web Pages 的合并是非常有可能的。 Web Pages 编程模型对当前版本来说还不适用,所以我们还不能负责任地说下一步计划合并哪些特性。 但是我们可以预测到,传统的 MVC 模型绑定将会出现。

View Components

在之前 ASP.NET MVC 中,, Html.Action() 帮助方法一般用于调用一个 sub-controller。ASP.NET MVC Core 将会使用新的 View Components 用来代替使用Html.Action() 的部件。

View Components 支持完全异步,这允许你创建异步的视图组件。

下面是一个简单的视图组件的例子,根据身份会返回个人介绍。

using Microsoft.AspNetCore.Mvc;  
using MVC6Demo.Models;  
using System.Threading.Tasks;  
using System.Collections.Generic;  
  
namespace MVC6Demo.ViewComponents  
{  
    public class PersonListViewComponent : ViewComponent  
    {  
        public async Task<iviewcomponentresult> InvokeAsync(string status) {  
            string viewToUse = "Default";  
            bool isFiltered = false;  
  
            PersonModel model = new PersonModel();  
  
            if (status.ToLower().Equals("registered")) { 
                viewToUse = "Registered"; isFiltered = true; 
            }  
                  
            var p = await GetPersonAsync(status, isFiltered);  
            return View(viewToUse,p);  
        }  
          
        private Task<ienumerable<person>> GetPersonAsync(string status, bool isFiltered) {  
            return Task.FromResult(GetPerson(status,isFiltered));  
        }  
        private IEnumerable<person> GetPerson(string status, bool isFiltered) {  
            PersonModel model = new PersonModel();  
  
            if (isFiltered)  
                return model.GetPersonsByStatus(status);  
            else  
                return model.GetAll;  
  
        }  
    }  
}  </person>

下面是 View Component 的视图:

<h3>Person List</h3>  
<ul>  
    @foreach (var p in Model) {  
        <li>@string.Format("{0} {1}",p.FirstName,p.LastName)</li>  
    }  
</ul> 

这里展示了如何在主视图中调用 View Components

<div>   
    @await Component.InvokeAsync("PersonList", new { type = "Registered" })
</div>  

新指令: @inject, @using, @inherits

ASP.NET MVC Core 提供了少量新指令。 下面我们来看看如何使用 @inject。 @inject 指令允许你注入一个类中的方法到你的视图中。

这是一个简单的类,来展示一些异步的方法。

using System.Threading.Tasks;  
using System.Linq;  
  
namespace MVC6Demo.Models  
{  
    public class Stats  
    {  
        private PersonModel _persons = new PersonModel();  
  
        public async Task<int> GetPersonCount() {  
            return await Task.FromResult(_persons.GetAll.Count());  
        }  
  
        public async Task<int> GetRegisteredPersonCount() {  
            return await Task.FromResult(
                      _persons.GetAll.Where(o => o.Status.ToLower().Equals("registered")).Count());  
        }  
  
        public async Task<int> GetUnRegisteredPersonCount() {  
            return await Task.FromResult(
                     _persons.GetAll.Where(o => o.Status.ToLower().Equals("")).Count());  
        }  
    }  
} 

现在我们就可以在视图中使用 @inject 指令来调用那些方法:

@inject MVC6Demo.Models.Stats Stats  
  
@{  
    ViewBag.Title = "Stats";  
}  
  
<div>  

这是不是很酷?

查看我关于 ASP.NET MVC 新指令详细例子的文章: Getting Started with ASP.NET MVC Core

Tag Helpers

ASP.NET MVC Core 另外一个非常酷的东西就是 Tag Helpers。对于之前的 HTML Helpers,Tag Helpers 是可选的替代语法。

所以相比于以下代码:

@using (Html.BeginForm("Login", "Account", FormMethod.Post, 
        new { @class = "form-horizontal", role = "form" }))
            {
                @Html.AntiForgeryToken()
                <h4>Use a local account to log in.</h4>
                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-group">
                    @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
                        @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
                    </div>
                </div>
}

你可以使用这些代码:

<form asp-controller="Account" asp-action="Login" method="post" class="form-horizontal" role="form">  
    <h4>Use a local account to log in.</h4>  
    <hr />  
    <div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>  
    <div class="form-group">  
        <label asp-for="UserName" class="col-md-2 control-label"></label>  
        <div class="col-md-10">  
            <input asp-for="UserName" class="col-md-2 control-label" />  
            <span asp-validation-for="UserName" class="text-danger"></span>  
        </div>  
    </div>  
</form> 

ASP.NET Core 不止可以部署在IIS上

14年前,ASP.NET 平台基本只能部署在一种服务器上,那就是 IIS。几年之后,Visual Studio Development Web Server(也叫作“Cassini”)作为一种开发服务被使用,但是它们最终都是调用 System.Web 作为应用程序和 Web 服务器中间的主机层。System.Web 主机与 IIS 耦合度很高,所以要想运行在另一台主机上会非常困难。

后来 OWIN 作为应用程序和 Web 服务器中间的接口出现。 Microsoft 开发了 Katana 作为一个 OWIN 的实现,可以部署 ASP.NET Web API, SignalR 和其他第三方框架,这些框架可以在 IIS 和 IIS Express, Katana's 自托管主机和自定义主机。

ASP.NET Core 是不强调主机的,它在 Katana 和 OWIN 上行为一致。ASP.NET Core 也可以部署在 IIS, IIS Express 或者自托管在你自己的进程里。另外,ASP.NET Core 也会包含一个叫做 Kestrel 的 Web 服务器,它建立在 libuv 上,主要用于 iOS 和 Linux 操作系统。

新的HTTP请求管道

ASP.NET Core 提供了一种更加模块化的 HTTP 请求管道, 你可以只添加你需要的组件。这个管道不再依赖 System.Web,通过降低管道中的开销,你的 app 性能更加优良,更好的调谐 HTTP 协议栈。新的管道基于 Katana 项目经验,同时支持 OWIN。

动态的Web开发

Visual Studio 2015 中另一个非常酷的特性就是支持动态编译。在过去的 ASP.NET 中,当我们修改了应用的后台代码,我们需要重新编译并且运行才能看到页面的变化。 在新版本的 Visual Studio 中,你不需要再做这些额外的步骤,仅仅是保存你的修改和刷新浏览器即可。

6

这是在刷新页面之后的输出:

7

Attribute Routing: [controller] 和 [action] 标记

在过去的 MVC 和 Web API 中,使用路由属性可能会导致一些问题,尤其是你正在做一些代码重构。这是因为路由必须设定为字符串类型,当你修改了控制器的名字,你就必须修改路由属性的字符串

MVC Core 提供了新的 [controller] 和 [action] 标记,它们可以解决这个问题。下面这篇文章重点说明了这些新标记的用法。 : ASP.NET MVC 6 Attribute Routing.

集成的依赖注入 (DI)

ASP.NET Core 内嵌了对依赖注入和 Service Locator 模式的支持,这意味着你不在需要通过第三方依赖注入框架 Ninject 或 AutoFac。

集成 Grunt, Gulp and Bower

Visual Studio 2015 内嵌了对流行开源 Web 开发工具的支持。 Grunt 和 Gulp 可以帮你自动化构建 Web 开发工作流, 你可以使用它们来编译和压缩 JavaScript 文件。Bower 是一个用于客户端库的管理工具,包含 CSS 和 JavaScript 库。

内置的AngularJs模板

AngularJs 是当前最流行的前端框架之一,用于构建单页面应用程序(SPAs)。Visual Studio 包含了用于创建 AngularJs 模块,控制器,指令和工厂。

8

对 GruntJS 的支持使得 ASP.NET 成为一个用于构建客户端 AngularJs 应用的优秀服务器端框架。 当完成一个版本,你可以自动合并和压缩全部 AngularJs 文件。查看我的关于开始在 ASP.NET 中使用 Angular 和 Angular2 的文章 。

· ASP.NET 5: Jump Start to AngularJS with MVC 6 Web API

· ASP.NET Core:Getting Started with AngularJS 2

SignalR 3

ASP.NET Core 也是以 SignalR 3 为基础,这使得你可以向云连接的应用程序添加实时功能。查看我之前的 SignalR 例子: ASP.Net SignalR: Building a Simple Real-Time Chat Application

Web.Config

在 ASP.NET Core 中,混乱的 web.config 文件被新的云就绪配置文件代替,它称作 “config.json”。微软希望开发人员更容易地在云中部署应用程序,并使得应用能够根据特殊环境自动的读取正确的配置参数。

这是一个新的配置文件的样子:

9

由于 ASP.NET Core 都是插件化的,你需要配置 Stratup 类的源代码,就像下面这样:

 public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        public IConfigurationRoot Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddTransient<MVC6Demo.Models.HeroStats>();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();


            app.UseMvc(m => {
                m.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action="Index"});
            });
        }

xUnit.Net: New unit testing tool for .NET

In previous ASP.NET MVC, the default test framework was the Visual Studio Unit Test Framework (sometimes called mstest), which used the [TestClass] and [TestMethod] attributes to describe a unit test.

ASP.NET Core uses  xUnit.net  as its unit testing framework. The framework uses the [Fact] attribute in place of the [TestMethod] attribute and also removes the reliance on the [TestClass] attribute.

Absolutely free and open source

Yes, ASP.NET Core is hosted on  GitHub as an open source project , you can view the source code, download and commit your changes.

I agree that open source .NET will make a lot of sense, it makes positive business sense and community sense, and I'm very grateful for the work Microsoft has done.

The introduction of the new features and new concepts of ASP.NET Core 1.0 above is to better help us develop with ASP.NET Core. At the same time, during the development process, we can also use some good tools to improve development efficiency, and Reduce the amount of code, such as  ComponentOne Studio for Asp.net MVC , which is compatible with ASP.NET Core RC2 version, is a fast and lightweight control to meet all the needs of users.

 

Article source: By  Vincent Maverick Durano10 Jun 2016 

Original link: http://www.codeproject.com/Articles/1104668/Introducing-ASP-NET-Core-The-New-ASP-NET-in-Town

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326679041&siteId=291194637