分享我对 ASP.NET vNext 的一些感受,也许多年回过头看 So Easy!

写在前面

阅读目录:

  ASP.NET vNext 发布已经过去了一个多月的时间,发布详情请访问:振奋人心呐!关于下一代.NET——ASP.NET vNext 的更多说明,当时看这完篇新闻的第一感觉就像文章标题一样“振奋人心”,其实每个人都有自己的感受,对于我来说,ASP.NET vNext 最大的特性就是跨平台(基于 Mono 运行时),试想下:作为.NET程序员,终于不被Java或C++程序员挑自己的短板,确实是蛮振奋人心的。当然,除了跨平台,使用 Roslyn 编译器动态编译(修改源代码,刷新页面即可)、云优先(Cloud First)、开源等等特性也是蛮重要的。

  以下内容,只是一些个人看法,仅供参考学习,也欢迎讨论指教。

Visual Studio "14" CTP

  Visual Studio "14" CTP(Community Technology Previews)是下一代 Visual Studio 的社区预览版,我个人认为 Visual Studio "14" CTP(以下简称:VS 14 CTP) 就是为 ASP.NET vNext 而量身定做的,当然也包含了其他模块,比如:Store Apps、Cloud等等,以下是关于VS 14 CTP 的版本描述:

CTPs are provided for testing and feedback purposes only. CTPs are unsupported, English-only releases. They are not subject to final validation and are not intended for use on production computers, or to create production code.

Installing a CTP release will place a computer in an unsupported state. For that reason, we recommend only installing CTP releases in a virtual machine, or on a computer that is available for reformatting.

Currently, Visual Studio "14" CTPs have known compatibility issues with previous releases of Visual Studio and should not be installed side-by-side on the same computer.

  从版本中可以看出,VS 14 CTP 仅用于测试和反馈,只提供英文版本,而且安装 VS 14 CTP 会和已有的 Visual Studio 版本冲突,也就是说安装 VS 14 CTP 要把电脑中 Visual Studio 其他版本卸载,才能进行安装。

  至于“installed side-by-side on the same computer”,因为是先安装的 VS 14 CTP,再安装的 Visual Studio 其他版本,暂时没发现异常情况。

  VS 14 CTP 创建 ASP.NET vNext 项目模块:

  VS 14 CTP 下载地址:

关于 ASP.NET vNext

  ASP.NET vNext 的发布文章称其为.NET下一代,其实我个人觉得并不准确,ASP.NET vNext 就像其名字一样,应该是 ASP.NET 的下一代版本。ASP.NET vNext 代表着.NET的未来的发展方向,比如说跨平台、开源等,也就是 vNext。关于 ASP.NET vNext,园中也有几位大神写过几篇介绍的文章,以下是个人整理关于 ASP.NET vNext 的一些特性(更新时间为6月3日):

  • MVC、 Web API 和 Web Pages合并成一个框架,称为 MVC 6。新的框架使用一组通用的抽象为路由、 行为选择、 筛选器、 模型绑定等等。

  • MVC 6 并不依赖于 System.Web,是一个更精简的框架,用更快的启动时间和内存占用较低(也就是“低内存消耗”以及“高吞吐量”)。

  • ASP.NET vNext 应用程序可以使用云优化(Cloud-Optimized.NET Framework大约 11 M的大小相比于 200 M的完整的框架,也是组成的 NuGet 包的集合(云优化的功劳)。

  • 云优化框架的减少使实际部署的应用程序框架

    • 在同一台服务器上,你可以使用不同版本的 Framework 运行应用程序。
    • 你的应用程序均从服务器上的架构更改,绝缘。
    • 你可以为每个应用程序的 Framework 更新自己的时间表。
    • 当你部署应用造成开发机器上的 Framework 修补程序级别和应用服务器之间不匹配的时候,不会出现任何错误(也就是“绝缘”的意思)。
  • 提供云优化 Framework 的 NuGet 包,可实现以下目标:

    • 按需加载,不必要的部分不会加载到应用程序中。
    • Framework 中,由于每个部分可以独立更新,微软可以将更新变的更快。
  • ASP.NET vNext 与 Host 无关。你可以承载你的应用程序在 IIS 中,或自托管在一个自定义的过程(web API 2 和 SignalR 2 已经支持自托管,ASP.NET vNext 也会给 MVC 带来同样的功能)

  • 支持依赖注入(也可以使用自己的 IoC 容器来注册依赖项)

  • ASP.NET vNext 使用 Roslyn 编译器动态编译代码。你可以编辑一个代码文件,刷新浏览器,并看到所做的更改,并没有重建项目。除了简化开发过程,动态代码编译在现在变得可能,如在 Visual Studio Online ("Monaco") 进行代码编写,你可以选择你自己的编辑器和工具。

  • ASP.NET vNext 开放源代码。

  • ASP.NET vNext 跨平台

  .NET未来构想图,对于 ASP.NET vNext 来说,可以看出尤其侧重于云优化-Cloud Optimized,包含高吞吐量低内存消耗、并行执行和跨平台

  ASP.NET vNext 成员图:

  从上图可以更直观的看出 ASP.NET vNext 所涵盖的东西,这样的统一管理,带给编程人员好处是很多的,比如:一路由系统、 一个模型绑定系统、 一个筛选器管道等,也可以完美的从 Web Pages 过渡到 MVC。

  .NET vNext 和 .NET vNext -云优化(包含模块)示意图:

  ASP.NET vNext 云优化示意图:

  代码到 Web 服务器示意图,”快速迭代式开发“,即修改代码刷新浏览器,接近实时,也可以实现”云编辑“功能:

  ASP.NET vNext 跨平台示意图:

ASP.NET vNext 实践

  关于 ASP.NET vNext 的实践,MSDN 已经更新了"Music Store"(音乐商店)项目,感兴趣的朋友可以参考练习下,下面做的 ASP.NET vNext 简单示例,只是个人的学习记录,方面以后自己查看,园友们可以直接略过。

  首先打开 VS 14 CTP,新建 ASP.NET vNext 项目。

  ASP.NET vNext 主要包含三类模板:

  • ASP.NET vNext Web Application:用于创建 Web 应用程序。
  • ASP.NET vNext Class Library:用于创建云优化类库项目。
  • ASP.NET vNext Console Application:用于创建控制台应用程序。

  新建 vNextDemo 项目后,发现目录结构非常简单.

  共包含两个项目文件:

  • project.json:配置应用程序所有依赖项。
  • Startup.cs:程序启动类。

project.json

  在 ASP.NET vNext 中看不到我们常用的 config 文件了,取而代之的是 json(或是其他文件类型)配置文件,例如用来配置连接字符串的 config.json 文件:

1 {
2     "Data": {
3         "DefaultConnection": { 
4             "ConnectionString": "Server=(localdb)\mssqllocaldb;Database=aspnetvnext-49333c44-d261-476e-b40a-3d9b759fc2da;Trusted_Connection=True;MultipleActiveResultSets=true"
5         }
6     }
7 }

  贴一段 project.json 示例配置

 1 {
 2     "dependencies": {
 3         "Helios": "0.1-alpha-build-0585",
 4         "Microsoft.AspNet.Mvc": "0.1-alpha-build-1268",
 5         "Microsoft.AspNet.Identity.Entity": "0.1-alpha-build-1059",
 6         "Microsoft.AspNet.Identity.Security": "0.1-alpha-build-1059",
 7         "Microsoft.AspNet.Security.Cookies": "0.1-alpha-build-0506",
 8         "Microsoft.AspNet.Server.WebListener": "0.1-alpha-build-0520",
 9         "Microsoft.AspNet.StaticFiles": "0.1-alpha-build-0443",
10         "Microsoft.Data.Entity": "0.1-alpha-build-0863",
11         "Microsoft.Data.Entity.SqlServer": "0.1-alpha-build-0863",
12         "Microsoft.Framework.ConfigurationModel.Json": "0.1-alpha-build-0233",
13         "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0-alpha"
14     },
15     "commands": {
16         /* Change the port number when you are self hosting this application */
17         "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
18     },
19     "configurations": {
20         "net45": {
21             "dependencies": {
22                 "System.Data": "",
23                 "System.ComponentModel.DataAnnotations": ""
24             }
25         },
26         "k10": {
27         }
28     }
29 }

  在 dependencies(依赖关系)节点,看起来有点像 NuGet 的 packages.config 配置包,但是不同之处是,以前版本中会直接添加这项项的引用,而且还取决于这些包,现在都是动态配置,比如删除一个引用,它会自动删除所依赖项,如果在 project.json 中未使用,也会动态的移除掉。

  除了 dependencies,还包含 commands(命令)和 configurations(配置)节点,commands 中的”web“配置表示,应用程序默认启动地址,configurations 中的”net45“表示完整的桌面应用程序,”k10“表示云优化。

Startup.cs

  Startup.cs 是整个应用程序的启动类,有点类似于我们常用的 Global.asax,贴一段示例代码(ASP.NET vNext Web Application):

 1 using System;
 2 using Microsoft.AspNet.Builder;
 3 using Microsoft.AspNet.Http;
 4 using Microsoft.AspNet.Identity;
 5 using Microsoft.AspNet.Identity.Security;
 6 using Microsoft.AspNet.Routing;
 7 using Microsoft.AspNet.Security.Cookies;
 8 using Microsoft.Data.Entity;
 9 using Microsoft.Framework.ConfigurationModel;
10 using Microsoft.Framework.DependencyInjection;
11 using WebApplication1.Models;
12 
13 namespace WebApplication1
14 {
15     public class Startup
16     {
17         public void Configure(IBuilder app)
18         {
19             // Enable Browser Link support
20             app.UseBrowserLink();
21 
22             // Setup configuration sources
23             var configuration = new Configuration();
24             configuration.AddJsonFile("config.json");
25             configuration.AddEnvironmentVariables();
26 
27             // Set up application services
28             app.UseServices(services =>
29             {
30                 // Add EF services to the services container
31                 services.AddEntityFramework()
32                     .AddSqlServer();
33 
34                 // Configure DbContext
35                 services.SetupOptions<DbContextOptions>(options =>
36                 {
37                     options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
38                 });
39                 
40                 // Add Identity services to the services container
41                 services.AddIdentity<ApplicationUser>()
42                     .AddEntityFramework<ApplicationUser, ApplicationDbContext>()
43                     .AddHttpSignIn();
44 
45                 // Add MVC services to the services container
46                 services.AddMvc();
47             });
48 
49             // Add static files to the request pipeline
50             app.UseStaticFiles();
51 
52             // Add cookie-based authentication to the request pipeline
53             app.UseCookieAuthentication(new CookieAuthenticationOptions
54             {
55                 AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
56                 LoginPath = new PathString("/Account/Login"),
57             });
58 
59             // Add MVC to the request pipeline
60             app.UseMvc(routes =>
61             {
62                 routes.MapRoute(
63                     name: "default", 
64                     template: "{controller}/{action}/{id?}",
65                     defaults: new { controller = "Home", action = "Index" });
66 
67                 routes.MapRoute(
68                     name: "api",
69                     template: "{controller}/{id?}");
70             });
71         }
72     }
73 }

  可以看出 Startup 的 Configure 方法包含一个 IBuilder 类型的参数,上段代码表示:

  • 添加浏览器链接

  • 配置系统配置,来自 config.json 和环境变量的值

  • 添加 EntityFramework

  • 添加 ASP.NET Identity

  • 添加 ASP.NET MVC

vNextDemo.kproj

  使用 VS 14 CTP 创建 ASP.NET vNext 项目的时候,会产生”.kproj“后缀的项目文件,有点类似于我们平常见到的”.csproj“文件,功能是差不多的,都是管理项目中文件,因为 ASP.NET vNext 将支持"云编辑",所以这种文件将在 VS 14 CTP 的后续版本中不复存在。

In this preview release you’ll find that all files in your project are listed in the .kproj file. In later versions the files will not be listed in the .kproj.

Views and Controller

  Views(视图)和 Controller(控制器)的创建和 ASP.NET MVC 差不多,贴一下简单示例代码:

  Views:

1 @*
2     For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
3 *@
4 @{
5     // Layout = "/Views/Shared/_Layout.cshtml";
6     // ViewBag.Title = "Home Page";
7 }
8 <h1>@ViewBag.Message</h1>

  Controller

 1 using Microsoft.AspNet.Mvc;
 2 
 3 // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
 4 
 5 namespace vNextDemo.Controllers
 6 {
 7     public class HelloWorldController : Controller
 8     {
 9         // GET: /<controller>/
10         public IActionResult Index()
11         {
12             ViewBag.Message = "Hello World";
13             return View();
14         }
15     }
16 }

  Views 和 Controller 创建完之后,需要在 project.json 文件中配置 MVC 依赖关系:"Microsoft.AspNet.Mvc": "0.1-alpha-build-1268",格式为:“项目名称”:“”,网上说支持智能提示(还有小图标显示),不知是不是我 VS 14 CTP 安装问题(好像安装完成后有个警告,当时没仔细看),导致没有智能提示。

Startup -> Configure

  上面基本代码编写完之后,需要在 Startup 中添加 MVC 及 MVC 路由配置,示例代码:

 1 using Microsoft.AspNet.Routing;
 2 using Microsoft.AspNet.Builder;
 3 using Microsoft.Framework.DependencyInjection;
 4 
 5 namespace vNextDemo
 6 {
 7     public class Startup
 8     {
 9         public void Configure(IBuilder app)
10         {
11             app.UseServices(services =>
12             {
13                 services.AddMvc();
14             });
15 
16             app.UseMvc(routes =>
17             {
18                 routes.MapRoute(
19                     name: "Default",
20                     template: "{controller}/{action}/{id?}",
21                     defaults: new { controller = "HelloWorld", action = "Index" });
22             });
23         }
24     }
25 }

Start

  直接运行调试:

  也可以通过 commands 配置 self-host,如下:

1     "commands": {
2         "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5000" 
3     },

  文件发布,也可以进行 Windows Azure 发布:

  Web Publish Activity 发布成功提示:

  点击发布文件中的“web.cmd”,过几秒提示“Started”,表示程序已启动,打开浏览器,输入:http://localhost:5000/,就可以浏览了。

  MSDN 中很多博文讲到命令行配置,也就是:kpm restore 或 k web,kpm restore 命令表示解析 project.json 文件中列出的依赖关系,并下载所需的 NuGet 包,k web 命令表示启动的 HTTP 侦听器,但文中没有详细的配置方法,如下:

  上述示例只是 ASP.NET vNext 的简单创建,并不包含其特性,贪多嚼不烂,关于 ASP.NET vNext 的特性应用后续探讨,比如跨平台、云优化等。

  示例代码下载:http://pan.baidu.com/s/1haagY

后记

  个人觉得性能和平台问题,一直是.NET的痛处,ASP.NET vNext 的发布让我们.NET狂热者看到了曙光,我觉得这不只是一个版本发布的问题,而是一个里程碑,可以载入.NET发展史册,虽然仅仅发布一个多月的时间,但是在 MSDN 中,关于 ASP.NET vNext,已经有超过7000多篇博文发表,也希望博客园的园友们可以贡献出自己的一份力量。

  凡事贵在开始,对于.NET的未来,我觉得 ASP.NET vNext 就是一个不错的开始。

  如果你觉得本篇文章对你有所帮助,请点击右下部“推荐”,^_^

  参考资料:

原文地址:https://www.cnblogs.com/xishuai/p/3782613.html