1. 程式人生 > >分享我對 ASP.NET vNext 的一些感受,也許多年回過頭看 So Easy!

分享我對 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 的特性應用後續探討,比如跨平臺、雲優化等。

後記

  個人覺得效能和平臺問題,一直是.NET的痛處,ASP.NET vNext 的釋出讓我們.NET狂熱者看到了曙光,我覺得這不只是一個版本釋出的問題,而是一個里程碑,可以載入.NET發展史冊,雖然僅僅釋出一個多月的時間,但是在 MSDN 中,關於 ASP.NET vNext,已經有超過7000多篇博文發表,也希望部落格園的園友們可以貢獻出自己的一份力量。

  凡事貴在開始,對於.NET的未來,我覺得 ASP.NET vNext 就是一個不錯的開始。

  如果你覺得本篇文章對你有所幫助,請點選右下部“推薦”,^_^

  參考資料: