實際操作實驗室:一個 ASP.NET:整合 ASP.NET Web Form、MVC 與 Web APIHands On Lab: One ASP.NET: Integrating ASP.NET Web Forms, MVC and Web API

藉由Web Camp 小組by Web Camps Team

下載 Web 研討會訓練套件Download Web Camps Training Kit

ASP.NET 是用於建置網站、 應用程式和服務使用特製化的技術,例如 MVC、 Web API 等的架構。ASP.NET is a framework for building Web sites, apps and services using specialized technologies such as MVC, Web API and others. 與延伸 ASP.NET 已經看到自建立後,表示需要有整合這些技術中已經有最新的工作來運作One ASP.NETWith the expansion ASP.NET has seen since its creation and the expressed need to have these technologies integrated, there have been recent efforts in working towards One ASP.NET.

Visual Studio 2013 導入了新的統一的專案系統可讓您建置應用程式和一個專案中使用所有的 ASP.NET 技術。Visual Studio 2013 introduces a new unified project system which lets you build an application and use all the ASP.NET technologies in one project. 這項功能就不需要在開始專案,並隨身碟,挑選一種技術,並改為鼓勵使用一個專案中的多個 ASP.NET 架構。This feature eliminates the need to pick one technology at the start of a project and stick with it, and instead encourages the use of multiple ASP.NET frameworks within one project.

所有的範例程式碼和程式碼片段會包含在 Web 研討會訓練套件,可在 https://aka.ms/webcamps-training-kit All sample code and snippets are included in the Web Camps Training Kit, available at https://aka.ms/webcamps-training-kit.

總覽Overview

目標Objectives

在這個實際操作實驗室中,您將了解如何:In this hands-on lab, you will learn how to:

  • 建立網站,根據One ASP.NET專案類型Create a Web site based on the One ASP.NET project type
  • 使用不同ASP.NET架構喜歡MVCWeb API相同專案中Use different ASP.NET frameworks like MVC and Web API in the same project
  • 識別的主要元件ASP.NET應用程式Identify the main components of an ASP.NET application
  • 善用ASP.NET Scaffolding架構,來自動建立控制器和檢視來執行 CRUD 作業會根據您的模型類別Take advantage of the ASP.NET Scaffolding framework to automatically create Controllers and Views to perform CRUD operations based on your model classes
  • 公開 (expose) 相同的機器和人類看得懂的格式為每個工作中使用正確的工具中的資訊集Expose the same set of information in machine- and human-readable formats using the right tool for each job

必要條件Prerequisites

需要下列項目才能完成這個實際操作實驗室:The following is required to complete this hands-on lab:

安裝程式Setup

若要在這個實際操作實驗室中執行的練習,您必須先設定您的環境。In order to run the exercises in this hands-on lab, you will need to set up your environment first.

  1. 開啟 Windows Explorer 並瀏覽至實驗室來源資料夾。Open Windows Explorer and browse to the lab's Source folder.
  2. 以滑鼠右鍵按一下Setup.cmd ,然後選取系統管理員身分執行來啟動安裝程序,將會設定您的環境並安裝這個實驗室的 Visual Studio 程式碼片段。Right-click on Setup.cmd and select Run as administrator to launch the setup process that will configure your environment and install the Visual Studio code snippets for this lab.
  3. 如果會顯示 [使用者帳戶控制] 對話方塊中,確認要繼續進行的動作。If the User Account Control dialog box is shown, confirm the action to proceed.

Note

請確定您執行安裝程式之前檢查這個實驗室的所有相依性。Make sure you have checked all the dependencies for this lab before running the setup.

使用程式碼片段Using the Code Snippets

整個實驗室文件中,您將會指示要插入程式碼區塊。Throughout the lab document, you will be instructed to insert code blocks. 為了方便起見,大部分的這段程式碼提供 Visual Studio 程式碼片段,您可以從 Visual Studio 2013,若要避免以手動方式新增內存取。For your convenience, most of this code is provided as Visual Studio Code Snippets, which you can access from within Visual Studio 2013 to avoid having to add it manually.

Note

每個練習會伴隨起始方案,位於開始練習,可讓您依照每個練習,獨立於其他的資料夾。Each exercise is accompanied by a starting solution located in the Begin folder of the exercise that allows you to follow each exercise independently of the others. 請留意練習期間新增的程式碼片段缺少這些啟動解決方案,並可能無法運作,直到您已完成練習。Please be aware that the code snippets that are added during an exercise are missing from these starting solutions and may not work until you have completed the exercise. 在練習的原始程式碼,您也可以找到結束資料夾包含 Visual Studio 方案,以程式碼所產生的相對應的練習中的步驟。Inside the source code for an exercise, you will also find an End folder containing a Visual Studio solution with the code that results from completing the steps in the corresponding exercise. 如果您需要其他說明,當您完成這個實際操作實驗室,您可以使用這些解決方案與指引。You can use these solutions as guidance if you need additional help as you work through this hands-on lab.


練習Exercises

這個實際操作實驗室還包含下列練習:This hands-on lab includes the following exercises:

  1. 建立新的 Web Form 專案Creating a New Web Forms Project
  2. 建立使用 Scaffolding MVC 控制器Creating an MVC Controller Using Scaffolding
  3. 建立使用 Scaffolding Web API 控制器Creating a Web API Controller Using Scaffolding

估計的時間才能完成這個實驗室:60 分鐘Estimated time to complete this lab: 60 minutes

Note

當您第一次啟動 Visual Studio 時,您必須選取其中一個預先定義的設定集合。When you first start Visual Studio, you must select one of the predefined settings collections. 每個預先定義的集合以符合特定的開發樣式設計,並決定視窗版面配置、 編輯器的行為、 IntelliSense 程式碼片段和對話方塊選項。Each predefined collection is designed to match a particular development style and determines window layouts, editor behavior, IntelliSense code snippets, and dialog box options. 在這個實驗室中的程序說明完成指定的工作,在 Visual Studio 中使用時所需的動作一般開發設定集合。The procedures in this lab describe the actions necessary to accomplish a given task in Visual Studio when using the General Development Settings collection. 如果您選擇不同的設定集合,您的開發環境,可能會有在步驟中,您應該考慮到的差異。If you choose a different settings collection for your development environment, there may be differences in the steps that you should take into account.

練習 1:建立新的 Web Form 專案Exercise 1: Creating a New Web Forms Project

在此練習中,您將建立新的 Web Form 網站,在 Visual Studio 2013 中使用One ASP.NET統一專案體驗,可讓您輕鬆地將相同的應用程式的 Web Form、 MVC 和 Web API 元件整合。In this exercise you will create a new Web Forms site in Visual Studio 2013 using the One ASP.NET unified project experience, which will allow you to easily integrate Web Forms, MVC and Web API components in the same application. 您接著會探索產生的方案,並找出其組件,和最後您會看到動作中的網站。You will then explore the generated solution and identify its parts, and finally you will see the Web site in action.

工作 1-建立新的站台使用一個 ASP.NET 使用經驗Task 1 – Creating a New Site Using the One ASP.NET Experience

在這項工作會啟動 Visual Studio 中建立新的網站為基礎One ASP.NET專案類型。In this task you will start creating a new Web site in Visual Studio based on the One ASP.NET project type. One ASP.NET統一所有 ASP.NET 技術,並可讓您混合及比對它們所需的選項。One ASP.NET unifies all ASP.NET technologies and gives you the option to mix and match them as desired. 然後辨識 live Web Form、 MVC 和 Web API 的不同元件並存應用程式內。You will then recognize the different components of Web Forms, MVC and Web API that live side by side within your application.

  1. 開啟Visual Studio Express 2013 for Web ,然後選取檔案 |新增專案... 啟動新的解決方案。Open Visual Studio Express 2013 for Web and select File | New Project... to start a new solution.

    建立新專案

    建立新的專案Creating a New Project

  2. 新的專案對話方塊中,選取ASP.NET Web 應用程式Visual C# |Web索引標籤,並確定 .NET Framework 4.5已選取。In the New Project dialog box, select ASP.NET Web Application under the Visual C# | Web tab, and make sure .NET Framework 4.5 is selected. 將專案命名為MyHybridSite,選擇位置然後按一下確定Name the project MyHybridSite, choose a Location and click OK.

    新的 ASP.NET Web 應用程式專案

    建立新的 ASP.NET Web 應用程式專案Creating a new ASP.NET Web Application project

  3. 新增 ASP.NET 專案對話方塊中,選取Web Form範本,然後選取MVCWeb API選項。In the New ASP.NET Project dialog box, select the Web Forms template and select the MVC and Web API options. 此外,請確定驗證選項設定為個別使用者帳戶Also, make sure that the Authentication option is set to Individual User Accounts. 按一下 [確定] 繼續操作。Click OK to continue.

    使用 Web Form 範本,包括 Web API 和 MVC 元件建立新的專案

    使用 Web Form 範本,包括 Web API 和 MVC 元件建立新的專案Creating a new project with the Web Forms template, including Web API and MVC components

  4. 您現在可以探索產生的方案結構。You can now explore the structure of the generated solution.

    探索產生的方案

    探索產生的方案Exploring the generated solution

    1. 帳戶: 此資料夾包含 Web 表單頁面,以註冊、 登入,以及管理應用程式的使用者帳戶。Account: This folder contains the Web Form pages to register, log in to and manage the application's user accounts. 此資料夾時就會加入個別使用者帳戶Web Form 專案範本在設定期間選取驗證選項。This folder is added when the Individual User Accounts authentication option is selected during the configuration of the Web Forms project template.
    2. 模型: 這個資料夾會包含代表您的應用程式資料的類別。Models: This folder will contain the classes that represent your application data.
    3. 控制站檢視:這些資料夾所需ASP.NET MVCASP.NET Web API元件。Controllers and Views: These folders are required for the ASP.NET MVC and ASP.NET Web API components. 您將探索的 MVC 和 Web API 的技術,在下一個練習中。You will explore the MVC and Web API technologies in the next exercises.
    4. Default.aspxContact.aspxabout.aspx 的網頁檔案是預先定義的 Web 表單頁面,您可以使用做為起點來建立特定頁面您應用程式。The Default.aspx, Contact.aspx and About.aspx files are pre-defined Web Form pages that you can use as starting points to build the pages specific to your application. 這些檔案的程式設計邏輯位於個別的檔案,稱為"程式碼後置"檔案,其有"。 aspx.cs"或"。 aspx.cs"延伸模組 (取決於使用語言)。The programming logic of those files resides in a separate file referred to as the "code-behind" file, which has an ".aspx.vb" or ".aspx.cs" extension (depending on the language used). 程式碼後置邏輯伺服器上執行,並以動態方式產生您頁面的 HTML 輸出。The code-behind logic runs on the server and dynamically produces the HTML output for your page.
    5. Site.MasterSite.Mobile.Master頁面定義應用程式中的外觀與風格及標準行為的所有頁面。The Site.Master and Site.Mobile.Master pages define the look and feel and the standard behavior of all the pages in the application.
  5. 按兩下Default.aspx瀏覽網頁的內容檔案。Double-click the Default.aspx file to explore the content of the page.

    瀏覽 Default.aspx 頁面

    瀏覽 Default.aspx 頁面Exploring the Default.aspx page

    Note

    網頁在檔案頂端的指示詞定義的 Web Form 網頁的屬性。The Page directive at the top of the file defines the attributes of the Web Forms page. 例如, MasterPageFile屬性會指定為主要路徑頁面-在此情況下, Site.Master頁面和Inherits屬性定義[繼承] 頁面的程式碼後置類別。For example, the MasterPageFile attribute specifies the path to the master page -in this case, the Site.Master page- and the Inherits attribute defines the code-behind class for the page to inherit. 此類別位於檔案取決於程式碼後置屬性。This class is located in the file determined by the CodeBehind attribute.

    Asp: Content控制項包含頁面 (文字、 標記和控制項) 的實際內容,且對應至asp: ContentPlaceHolder主版頁面上的控制項。The asp:Content control holds the actual content of the page (text, markup and controls) and is mapped to a asp:ContentPlaceHolder control on the master page. 在此情況下,將呈現頁面內容內MainContent中所定義的控制項Site.Master頁面。In this case, the page content will be rendered inside the MainContent control defined in the Site.Master page.

  6. 依序展開應用程式_開始資料夾,請注意WebApiConfig.cs檔案。Expand the App_Start folder and notice the WebApiConfig.cs file. Visual Studio 中產生的方案包含該檔案,因為 One ASP.NET 範本與設定您的專案時,包含 Web API。Visual Studio included that file in the generated solution because you included Web API when configuring your project with the One ASP.NET template.

  7. 開啟WebApiConfig.cs檔案。Open the WebApiConfig.cs file. WebApiConfig類別,您會發現與 Web API,相關聯的對應 HTTP 組態將路由傳送至Web API 控制器In the WebApiConfig class you will find the configuration associated with Web API, which maps HTTP routes to Web API controllers.

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
    
        // Web API routes
        config.MapHttpAttributeRoutes();
    
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    }
    
  8. 開啟RouteConfig.cs檔案。Open the RouteConfig.cs file. 內部RegisterRoutes方法,您會發現與 MVC,這會對應至 HTTP 路由相關聯的組態MVC 控制器Inside the RegisterRoutes method you will find the configuration associated with MVC, which maps HTTP routes to MVC controllers.

    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );
    }
    

工作 2-執行解決方案Task 2 – Running the Solution

在這項工作中,您將會執行產生的方案,瀏覽應用程式和其部分功能,例如重新撰寫 URL 和內建的驗證。In this task you will run the generated solution, explore the app and some of its features, like URL rewriting and built-in authentication.

  1. 若要執行此方案,請按F5或按開始按鈕位於工具列上。To run the solution, press F5 or click the Start button located on the toolbar. 應用程式首頁應該會在瀏覽器中開啟。The application home page should open in the browser.

    執行解決方案

  2. 確認 Web Form 網頁,會叫用。Verify that the Web Forms pages are being invoked. 若要這樣做,請附加 /contact.aspx url 網址列,然後按下EnterTo do this, append /contact.aspx to the URL in the address bar and press Enter.

    易記 Url

    易記 UrlFriendly URLs

    Note

    如您所見,URL 變更為 /連絡As you can see, the URL changes to /contact. 從開始ASP.NET 4、 URL 路由的功能已新增至 Web Form、 Url,您可以撰寫喜歡* http://www.mysite.com/products/software * 而不是 http://www.mysite.com/products.aspx?category=software.Starting from ASP.NET 4, URL routing capabilities were added to Web Forms, so you can write URLs like http://www.mysite.com/products/software instead of http://www.mysite.com/products.aspx?category=software. 如需詳細資訊請參閱URL 路由For more information refer to URL Routing.

  3. 現在,您將探索整合到應用程式的驗證流程。You will now explore the authentication flow integrated into the application. 若要這樣做,請按一下註冊頁面右上角。To do this, click Register in the upper-right corner of the page.

    註冊新的使用者

    註冊新的使用者Registering a new user

  4. 註冊頁面上,輸入使用者名稱密碼,然後按一下註冊In the Register page, enter a User name and Password, and then click Register.

    註冊頁面

    註冊頁面Register page

  5. 應用程式註冊新的帳戶,並驗證使用者。The application registers the new account, and the user is authenticated.

    已驗證的使用者

    已驗證的使用者User authenticated

  6. 請返回 Visual Studio,然後按SHIFT + F5停止偵錯。Go back to Visual Studio and press SHIFT + F5 to stop debugging.

練習 2:建立使用 Scaffolding MVC 控制器Exercise 2: Creating an MVC Controller Using Scaffolding

在這個練習中您會利用 Visual Studio 建立 ASP.NET MVC 5 控制器與動作和 Razor 檢視,以執行 CRUD 作業,而不需要撰寫一行程式碼提供的 ASP.NET Scaffold 架構。In this exercise you will take advantage of the ASP.NET Scaffolding framework provided by Visual Studio to create an ASP.NET MVC 5 controller with actions and Razor views to perform CRUD operations, without writing a single line of code. Scaffolding 程序將使用 Entity Framework Code First 來產生 SQL database 中的 資料內容和資料庫結構描述。The scaffolding process will use Entity Framework Code First to generate the data context and the database schema in the SQL database.

有關 Entity Framework Code FirstAbout Entity Framework Code First

Entity Framework (EF) 是物件關聯式對應程式 (ORM),可讓您使用而不是直接使用關聯式儲存結構描述的程式設計概念應用程式模型進行程式設計來建立資料存取應用程式。Entity Framework (EF) is an object-relational mapper (ORM) that enables you to create data access applications by programming with a conceptual application model instead of programming directly using a relational storage schema.

Entity Framework Code First 模型化工作流程可讓您使用您自己的網域類別代表模型執行查詢時,EF 相依於變更追蹤和更新函式。The Entity Framework Code First modeling workflow allows you to use your own domain classes to represent the model that EF relies on when performing querying, change-tracking and updating functions. 使用 Code First 開發工作流程,您不需要藉由建立資料庫,或指定的結構描述開始您的應用程式。Using the Code First development workflow, you do not need to begin your application by creating a database or specifying a schema. 相反地,您可以撰寫標準的.NET 類別可定義應用程式最適當的網域模型物件和 Entity Framework 會為您建立資料庫。Instead, you can write standard .NET classes that define the most appropriate domain model objects for your application, and Entity Framework will create the database for you.

Note

您可以深入了解 Entity Framework此處You can learn more about Entity Framework here.

工作 1-建立新模型Task 1 – Creating a New Model

您現在將會定義人員類別,將會用來建立 MVC 控制器和檢視的 scaffolding 程序的模型。You will now define a Person class, which will be the model used by the scaffolding process to create the MVC controller and the views. 您會先建立人員模型類別,在控制器中的 CRUD 作業將會自動建立和使用 scaffolding 功能。You will start by creating a Person model class, and the CRUD operations in the controller will be automatically created using scaffolding features.

  1. 開啟Visual Studio Express 2013 for WebMyHybridSite.sln解決方案位於來源/Ex2-MvcScaffolding/開始資料夾。Open Visual Studio Express 2013 for Web and the MyHybridSite.sln solution located in the Source/Ex2-MvcScaffolding/Begin folder. 或者,您可以繼續使用解決方案您在前一個練習中取得。Alternatively, you can continue with the solution that you obtained in the previous exercise.

  2. 在 [方案總管] 中,以滑鼠右鍵按一下模型資料夾MyHybridSite專案,然後選取新增 |類別....In Solution Explorer, right-click the Models folder of the MyHybridSite project and select Add | Class....

    新增人員模型類別

    新增人員模型類別Adding the Person model class

  3. 在 [加入新項目] 對話方塊中,將檔案命名Person.cs然後按一下新增In the Add New Item dialog box, name the file Person.cs and click Add.

    建立 Person 模型類別

    建立 Person 模型類別Creating the Person model class

  4. 取代的內容Person.cs為下列程式碼的檔案。Replace the content of the Person.cs file with the following code. 按下CTRL + S以儲存變更。Press CTRL + S to save the changes.

    (程式碼片段- BringingTogetherOneAspNet-Ex2-PersonClass)(Code Snippet - BringingTogetherOneAspNet - Ex2 - PersonClass)

    namespace MyHybridSite.Models
    {
        public class Person
        {
            public int Id { get; set; }
    
            public string Name { get; set; }
    
            public int Age { get; set; }
        }
    }
    
  5. 在 [方案總管] 中,以滑鼠右鍵按一下MyHybridSite專案,然後選取建置,或按CTRL + SHIFT + B來建置專案。In Solution Explorer, right-click the MyHybridSite project and select Build, or press CTRL + SHIFT + B to build the project.

工作 2-建立 MVC 控制器Task 2 – Creating an MVC Controller

既然Person建立模型,您將使用 Entity Framework 使用 ASP.NET MVC scaffolding,若要建立的 CRUD 控制器動作和檢視人員Now that the Person model is created, you will use ASP.NET MVC scaffolding with Entity Framework to create the CRUD controller actions and views for Person.

  1. 在 [方案總管] 中,以滑鼠右鍵按一下控制站資料夾MyHybridSite專案,然後選取新增 |新增 Scaffold 項目....In Solution Explorer, right-click the Controllers folder of the MyHybridSite project and select Add | New Scaffolded Item....

    建立新的 scaffold 的控制器

    建立新的 Scaffold 控制器Creating a new Scaffolded Controller

  2. 新增 Scaffold對話方塊中,選取使用 MVC 5 控制器與檢視,Entity Framework ,然後按一下 新增。In the Add Scaffold dialog box, select MVC 5 Controller with views, using Entity Framework and then click Add.

    選取具有檢視和 Entity Framework 的 MVC 5 控制器

    選取具有檢視和 Entity Framework 的 MVC 5 控制器Selecting MVC 5 Controller with views and Entity Framework

  3. 設定MvcPersonController作為控制站名稱,選取使用非同步控制器動作選項,然後選取人員 (MyHybridSite.Models) 作為模型類別Set MvcPersonController as the Controller name, select the Use async controller actions option and select Person (MyHybridSite.Models) as the Model class.

    新增 scaffolding MVC 控制器

    新增 scaffolding MVC 控制器Adding an MVC controller with scaffolding

  4. 底下資料內容類別,按一下 新資料內容....Under Data context class, click New data context....

    建立新的資料內容

    建立新的資料內容Creating a new data context

  5. 新的資料內容 對話方塊中,名稱的新資料內容PersonContext ,按一下 新增In the New Data Context dialog box, name the new data context PersonContext and click Add.

    建立新的 PersonContext

    建立新的 PersonContext 類型Creating the new PersonContext type

  6. 按一下 新增若要建立的新控制器人員使用 scaffolding。Click Add to create the new controller for Person with scaffolding. Visual Studio 接著會產生控制器動作、 個人資料內容和 Razor 檢視。Visual Studio will then generate the controller actions, the Person data context and the Razor views.

    在之後使用 scaffolding 建立 MVC 控制器

    在之後使用 scaffolding 建立 MVC 控制器After creating the MVC controller with scaffolding

  7. 開啟MvcPersonController.cs中的檔案控制站資料夾。Open the MvcPersonController.cs file in the Controllers folder. 請注意有自動產生的 CRUD 動作方法。Notice that the CRUD action methods have been generated automatically.

    ...
    
    // POST: /MvcPerson/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include="Id,Name,Age")] Person person)
    {
         if (ModelState.IsValid)
         {
              db.People.Add(person);
              await db.SaveChangesAsync();
              return RedirectToAction("Index");
         }
    
         return View(person);
    }
    
    // GET: /MvcPerson/Edit/5
    public async Task<ActionResult> Edit(int? id)
    {
         if (id == null)
         {
              return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
         Person person = await db.People.FindAsync(id);
         if (person == null)
         {
              return HttpNotFound();
         }
         return View(person);
    }
    
    ...
    

    Note

    藉由選取使用非同步控制器動作從 scaffolding 的核取方塊選項,在先前步驟中,Visual Studio 產生的所有動作涉及之存取權的個人資料內容的非同步動作方法。By selecting the Use async controller actions check box from the scaffolding options in the previous steps, Visual Studio generates asynchronous action methods for all actions that involve access to the Person data context. 建議您用於長時間執行非同步動作方法,不受限於 CPU 以避免封鎖在處理要求時執行工作的 Web 伺服器的要求。It is recommended that you use asynchronous action methods for long-running, non-CPU bound requests to avoid blocking the Web server from performing work while the request is being processed.

工作 3-執行解決方案Task 3 – Running the Solution

在這個工作中,您將執行一次以確認解決方案的檢視人員會如預期般運作。In this task, you will run the solution again to verify that the views for Person are working as expected. 您將加入新的對方,以確認它已成功儲存到資料庫。You will add a new person to verify that it is successfully saved to the database.

  1. 按下F5執行方案。Press F5 to run the solution.

  2. 瀏覽至 /MvcPersonNavigate to /MvcPerson. 包含 scaffold 的檢視,其顯示的人員清單應該會出現。The scaffolded view that shows the list of people should appear.

  3. 按一下 新建來新增新的人員。Click Create New to add a new person.

    瀏覽至包含 scaffold 的 MVC 檢視

    瀏覽至包含 scaffold 的 MVC 檢視Navigating to the scaffolded MVC views

  4. 建立檢視中,提供名稱年齡人,然後按一下 建立In the Create view, provide a Name and an Age for the person, and click Create.

    加入新的人員

    加入新的人員Adding a new person

  5. 新的人員新增至清單。The new person is added to the list. 在 [項目] 清單中,按一下詳細資料顯示連絡人的詳細資料檢視。In the element list, click Details to display the person's details view. 然後,在詳細資料檢視中,按一下回到清單返回清單檢視。Then, in the Details view, click Back to List to go back to the list view.

    人員詳細資料檢視

    人員詳細資料檢視Person's details view

  6. 按一下 刪除若要刪除之人員的連結。Click the Delete link to delete the person. 刪除檢視中,按一下刪除以確認此作業。In the Delete view, click Delete to confirm the operation.

    刪除使用者

    刪除使用者Deleting a person

  7. 請返回 Visual Studio,然後按SHIFT + F5停止偵錯。Go back to Visual Studio and press SHIFT + F5 to stop debugging.

練習 3:建立使用 Scaffolding Web API 控制器Exercise 3: Creating a Web API Controller Using Scaffolding

Web API 架構是 ASP.NET 堆疊的一部分,並可輕鬆實作 HTTP 服務,通常傳送和接收 JSON 或 XML 格式的資料,透過 RESTful API。The Web API framework is part of the ASP.NET Stack and designed to make implementing HTTP services easier, generally sending and receiving JSON- or XML-formatted data through a RESTful API.

在此練習中,您將使用 ASP.NET Scaffolding 一次產生 Web API 控制器。In this exercise, you will use ASP.NET Scaffolding again to generate a Web API controller. 您將使用相同PersonPersonContext從先前的練習,以提供相同的個人資料,以 JSON 格式的類別。You will use the same Person and PersonContext classes from the previous exercise to provide the same person data in JSON format. 您會看到如何公開相同的資源,以及在相同的 ASP.NET 應用程式內不同的方式。You will see how you can expose the same resources in different ways within the same ASP.NET application.

工作 1-建立 Web API 控制器Task 1 – Creating a Web API Controller

在這項工作會建立新Web API 控制器,將會公開 (expose) 電腦可使用格式 JSON 等個人資料。In this task you will create a new Web API Controller that will expose the person data in a machine-consumable format like JSON.

  1. 如果尚未開啟,請開啟Visual Studio Express 2013 for Web ,然後開啟MyHybridSite.sln解決方案位於來源/Ex3-WebAPI/開始資料夾。If not already opened, open Visual Studio Express 2013 for Web and open the MyHybridSite.sln solution located in the Source/Ex3-WebAPI/Begin folder. 或者,您可以繼續使用解決方案您在前一個練習中取得。Alternatively, you can continue with the solution that you obtained in the previous exercise.

    Note

    如果您開始從練習 3 開始方案時,請按CTRL + SHIFT + B建置方案。If you start with the Begin solution from Exercise 3, press CTRL + SHIFT + B to build the solution.

  2. 在 [方案總管] 中,以滑鼠右鍵按一下控制站資料夾MyHybridSite專案,然後選取新增 |新增 Scaffold 項目....In Solution Explorer, right-click the Controllers folder of the MyHybridSite project and select Add | New Scaffolded Item....

    建立新的 scaffold 的控制器

    建立新的 scaffold 的控制器Creating a new scaffolded Controller

  3. 新增 Scaffold對話方塊中,選取Web API左窗格中,然後Web API 2 控制器與動作,使用 Entity Framework在中間窗格中,然後按一下 新增。In the Add Scaffold dialog box, select Web API in the left pane, then Web API 2 Controller with actions, using Entity Framework in the middle pane and then click Add.

    選取 Web API 2 控制器與動作和 Entity FrameworkSelecting Web API 2 Controller with actions and Entity Framework

    選取 Web API 2 控制器與動作和 Entity FrameworkSelecting Web API 2 Controller with actions and Entity Framework

  4. 設定ApiPersonController作為控制站名稱,選取使用非同步控制器動作選項,然後選取人員 (MyHybridSite.Models)PersonContext (MyHybridSite.Models) 作為模型資料內容分別為類別。Set ApiPersonController as the Controller name, select the Use async controller actions option and select Person (MyHybridSite.Models) and PersonContext (MyHybridSite.Models) as the Model and Data context classes respectively. 然後按一下 [加入] 。Then click Add.

    新增 scaffolding Web API 控制器Adding a Web API Controller with scaffolding

    新增 scaffolding Web API 控制器Adding a Web API controller with scaffolding

  5. Visual Studio 接著會產生ApiPersonController執行四個的 CRUD 動作,以處理資料的類別。Visual Studio will then generate the ApiPersonController class with the four CRUD actions to work with your data.

    使用 scaffolding 建立 Web API 控制器之後After creating the Web API controller with scaffolding

    在之後使用 scaffolding 建立 Web API 控制器After creating the Web API controller with scaffolding

  6. 開啟ApiPersonController.cs檔案,並檢查GetPeople動作方法。Open the ApiPersonController.cs file and inspect the GetPeople action method. 這個方法會查詢的資料庫欄位PersonContext以取得使用者的資料類型。This method queries the db field of PersonContext type in order to get the people data.

    // GET api/ApiPerson
    public IQueryable<Person> GetPeople()
    {
        return db.People;
    }
    
  7. 現在注意到方法定義上方的註解。Now notice the comment above the method definition. 它會提供您將在下一個工作使用此動作公開 (expose) 的 URI。It provides the URI that exposes this action which you will use in the next task.

    // GET api/ApiPerson
    public IQueryable<Person> GetPeople()
    {
        return db.People;
    }
    

    Note

    根據預設,Web API 已攔截到的查詢 /api路徑,以避免與 MVC 控制器的衝突。By default, Web API is configured to catch the queries to the /api path to avoid collisions with MVC controllers. 如果您需要變更此設定,請參閱ASP.NET Web API 中的路由If you need to change this setting, refer to Routing in ASP.NET Web API.

工作 2-執行解決方案Task 2 – Running the Solution

在這項工作中,您將使用 Internet Explorer F12 開發人員工具檢查 Web API 控制器的完整回應。In this task you will use the Internet Explorer F12 developer tools to inspect the full response from the Web API controller. 您會看到如何您也可以擷取網路流量,以取得您的應用程式資料的更多見解。You will see how you can capture network traffic to get more insight into your application data.

Note

請確定Internet Explorer中選取開始位於 Visual Studio 工具列上的按鈕。Make sure that Internet Explorer is selected in the Start button located on the Visual Studio toolbar.

Internet Explorer 選項

F12 開發人員工具有一組廣泛的並未涵蓋此實際操作實驗室的功能。The F12 developer tools have a wide set of functionality that is not covered in this hands-on-lab. 如果您想要深入了解,請參閱使用 F12 開發人員工具If you want to learn more about it, refer to Using the F12 developer tools.

  1. 按下F5執行方案。Press F5 to run the solution.

    Note

    若要正確遵循這項工作中,您的應用程式需要有資料。In order to follow this task correctly, your application needs to have data. 如果您的資料庫是空的您可以返回練習 2 中的工作 3,並遵循上如何建立使用 MVC 檢視的新使用者的步驟。If your database is empty, you can go back to Task 3 in Exercise 2 and follow the steps on how to create a new person using the MVC views.

  2. 在瀏覽器中,按下F12來開啟開發人員工具面板。In the browser, press F12 to open the Developer Tools panel. 按下CTRL + 4 ,或按一下網路圖示,然後按一下綠色箭號按鈕以開始擷取網路流量。Press CTRL + 4 or click the Network icon, and then click the green arrow button to begin capturing network traffic.

    起始 Web API 網路擷取Initiating Web API network capture

    起始的 Web API 網路擷取Initiating Web API network capture

  3. 附加api/ApiPerson至瀏覽器的網址列中的 URL。Append api/ApiPerson to the URL in the browser's address bar. 您現在會檢查來自回應的詳細資料ApiPersonControllerYou will now inspect the details of the response from the ApiPersonController.

    擷取使用者資料透過 Web APIRetrieving person data through Web API

    擷取透過 Web API 的個人資料Retrieving person data through Web API

    Note

    下載完成後,系統會提示您使用下載的檔案進行的動作。Once the download finishes, you will be prompted to make an action with the downloaded file. 讓對話方塊保持開啟,才能夠觀賞回應內容,透過開發人員工具視窗。Leave the dialog box open in order to be able to watch the response content through the Developers Tool window.

  4. 現在,您將會檢查回應的主體。Now you will inspect the body of the response. 若要這樣做,請按一下詳細資料索引標籤,然後按一下回應主體To do this, click the Details tab and then click Response body. 您可以檢查已下載的資料是否具有屬性的物件清單識別碼名稱年齡對應到人員類別。You can check that the downloaded data is a list of objects with the properties Id, Name and Age that correspond to the Person class.

    檢視 Web API 回應主體Viewing Web API Response Body

    檢視 Web API 回應主體Viewing Web API Response Body

工作 3-新增 Web API 說明頁面Task 3 – Adding Web API Help Pages

當您建立 Web API 時,最好建立說明頁面,讓其他開發人員都知道如何呼叫您的 API。When you create a Web API, it is useful to create a help page so that other developers will know how to call your API. 您可以建立並手動更新文件頁面,但最好是自動產生以避免需要進行的維護工作。You could create and update the documentation pages manually, but it is better to auto-generate them to avoid having to do maintenance work. 在這項工作中,您將使用的 Nuget 套件來自動產生方案的 Web API 說明頁面。In this task you will use a Nuget package to automatically generate Web API help pages to the solution.

  1. 工具功能表,在 Visual Studio 中,選取NuGet 套件管理員,然後按一下Package Manager ConsoleFrom the Tools menu in Visual Studio, select NuGet Package Manager, and then click Package Manager Console.

  2. 在 [ Package Manager Console ] 視窗中,執行下列命令:In the Package Manager Console window, execute the following command:

    Install-Package Microsoft.AspNet.WebApi.HelpPage
    

    Note

    Microsoft.AspNet.WebApi.HelpPage套件會安裝必要的組件,並且新增 MVC 檢視底下的 [說明] 頁區域/HelpPage資料夾。The Microsoft.AspNet.WebApi.HelpPage package installs the necessary assemblies and adds MVC Views for the help pages under the Areas/HelpPage folder.

    HelpPage 區域HelpPage Area

    HelpPage 區域HelpPage Area

  3. 根據預設,說明 頁面都有文件的預留位置字串。By default, the help pages have placeholder strings for documentation. 若要建立文件,您可以使用 XML 文件註解。You can use XML documentation comments to create the documentation. 若要啟用這項功能,請開啟HelpPageConfig.cs檔案位於應用程式的區域/HelpPage_啟動資料夾並取消註解下面這一行:To enable this feature, open the HelpPageConfig.cs file located in the Areas/HelpPage/App_Start folder and uncomment the following line:

    config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
    
  4. 在 [方案總管] 中,以滑鼠右鍵按一下專案MyHybridSite,選取屬性,按一下 [建置] 索引標籤。In Solution Explorer, right-click the project MyHybridSite, select Properties and click the Build tab.

    建置索引標籤Build tab

    建置索引標籤Build tab

  5. 底下輸出,選取XML 文件檔案Under Output, select XML documentation file. 在 [編輯] 方塊中,鍵入應用程式_Data/XmlDocument.xmlIn the edit box, type App_Data/XmlDocument.xml.

    輸出 [建置] 索引標籤中的一節Output section in Build tab

    在 [建置] 索引標籤的 [輸出] 區段Output section in Build tab

  6. 按下CTRL + S以儲存變更。Press CTRL + S to save the changes.

  7. 開啟ApiPersonController.cs檔案控制站資料夾。Open the ApiPersonController.cs file from the Controllers folder.

  8. 輸入新的一行之間GetPeople方法簽章並有 / / 取得 api/ApiPerson註解,然後輸入 三個正斜線。Enter a new line between the GetPeople method signature and the // GET api/ApiPerson comment, and then type three forward slashes.

    Note

    Visual Studio 會自動插入的 XML 項目會定義方法的文件。Visual Studio automatically inserts the XML elements which define the method documentation.

  9. 新增摘要的文字和傳回值GetPeople方法。Add a summary text and the return value for the GetPeople method. 它看起來應該如下所示。It should look like the following.

    // GET api/ApiPerson
    /// <summary>
    /// Documentation for 'GET' method
    /// </summary>
    /// <returns>Returns a list of people in the requested format</returns>
    public IQueryable<Person> GetPeople()
    {
        return db.People;
    }
    
  10. 按下F5執行方案。Press F5 to run the solution.

  11. 附加 /help [網址] 列中的 url,瀏覽至 [說明] 頁面。Append /help to the URL in the address bar to browse to the help page.

    ASP.NET Web API 說明頁面ASP.NET Web API Help Page

    ASP.NET Web API 說明頁面ASP.NET Web API Help Page

    Note

    主頁面的內容是依控制站的 api 的資料表。The main content of the page is a table of APIs, grouped by controller. 資料表項目使用,以動態方式產生IApiExplorer介面。The table entries are generated dynamically, using the IApiExplorer interface. 如果您新增或更新 API 控制器,資料表會自動更新您建置應用程式在下一次。If you add or update an API controller, the table will be automatically updated the next time you build the application.

    API欄會列出的 HTTP 方法和相對 URI。The API column lists the HTTP method and relative URI. 描述資料行包含已從方法的文件中擷取的資訊。The Description column contains information that has been extracted from the method's documentation.

  12. 請注意您新增上述的方法定義的描述會顯示在 [描述] 欄中。Note that the description you added above the method definition is displayed in the description column.

    API 方法描述API method description

    API 方法的描述API method description

  13. 按一下其中一個 API 方法,以便瀏覽至含有更多詳細資訊,包括範例回應主體的頁面。Click one of the API methods to navigate to a page with more detailed information, including sample response bodies.

    詳細資料 頁Detail Information page

    詳細的資訊 頁面Detailed information page


總結Summary

藉由完成這個實際操作實驗室,您已經學會如何:By completing this hands-on lab you have learned how to:

  • 建立新的 Web 應用程式,Visual Studio 2013 中使用一個 ASP.NET 使用經驗Create a new Web application using the One ASP.NET Experience in Visual Studio 2013
  • 將多個 ASP.NET 技術整合到一個單一專案Integrate multiple ASP.NET technologies into one single project
  • 從您的模型類別使用的 ASP.NET Scaffold 產生 MVC 控制器和檢視Generate MVC controllers and views from your model classes using ASP.NET Scaffolding
  • 產生使用功能,例如非同步程式設計,並透過 Entity Framework 資料存取的 Web API 控制器Generate Web API controllers, which use features such as Async Programming and data access through Entity Framework
  • 自動產生 Web API 說明頁面,您的控制站Automatically generate Web API Help Pages for your controllers