建置使用 ASP.NET Web API 的 RESTful ApiBuild RESTful APIs with ASP.NET Web API

藉由Web Camp 小組by Web Camps Team

近年來,它具有一目了然,HTTP 不只是提供 HTML 頁面。In recent years, it has become clear that HTTP is not just for serving up HTML pages. 它也是強大的平台,建置 Web Api,使用少數幾個動詞 (GET、 POST 等) 再加上幾個簡單的概念,例如Uri標頭It is also a powerful platform for building Web APIs, using a handful of verbs (GET, POST, and so forth) plus a few simple concepts such as URIs and headers. ASP.NET Web API 是一組簡化 HTTP 程式設計的元件。ASP.NET Web API is a set of components that simplify HTTP programming. 由於它建置在 ASP.NET MVC 執行階段上,Web API 會自動處理 HTTP 傳輸低階詳細資料。Because it is built on top of the ASP.NET MVC runtime, Web API automatically handles the low-level transport details of HTTP. 在此同時,Web API,自然地公開 HTTP 程式設計模型。At the same time, Web API naturally exposes the HTTP programming model. 事實上,Web API 的其中一個目標是要摘除 HTTP 的事實。In fact, one goal of Web API is to not abstract away the reality of HTTP. 如此一來,Web API 是彈性且容易擴充。As a result, Web API is both flexible and easy to extend. 在這個實際操作實驗室中,您將使用 Web API 來建置簡單的 REST API 連絡人管理員應用程式。In this hands-on lab, you will use Web API to build a simple REST API for a contact manager application. 您也將建置的用戶端取用 API。You will also build a client to consume the API. 事實證明的 REST 架構樣式會運用 HTTP-的有效方法,但是它當然不是 HTTP 的唯一有效方法。The REST architectural style has proven to be an effective way to leverage HTTP - although it is certainly not the only valid approach to HTTP. 連絡人的管理員會公開清單、 加入和移除連絡人,以及其他符合 rest 限制。The contact manager will expose the RESTful for listing, adding and removing contacts, among others. 這個實驗室需要基本 HTTP,其餘部分,了解,並假設您有基本的 HTML、 JavaScript 和 jQuery 的實用知識。This lab requires a basic understanding of HTTP, REST, and assumes you have a basic working knowledge of HTML, JavaScript, and jQuery.

注意

ASP.NET 網站有一個專門用來在 ASP.NET Web API 架構的區域 https://asp.net/web-api The ASP.NET Web site has an area dedicated to the ASP.NET Web API framework at https://asp.net/web-api. 此站台將持續提供最新的資訊、 範例和新聞與 Web API,因此請經常如果您想要更深入地鑽研建立給幾乎任何裝置或開發架構,可用的自訂 Web Api 的圖案。This site will continue to provide late-breaking information, samples, and news related to Web API, so check it frequently if you'd like to delve deeper into the art of creating custom Web APIs available to virtually any device or development framework.

ASP.NET Web API,類似於 ASP.NET MVC 4 中,有很大的彈性方面開來,讓您可以使用數個可用的相依性插入架構相當簡單的控制站的服務層。ASP.NET Web API, similar to ASP.NET MVC 4, has great flexibility in terms of separating the service layer from the controllers allowing you to use several of the available Dependency Injection frameworks fairly easy. 示範如何使用 Ninject 相依性插入,您可以下載從 ASP.NET Web API 專案中的 MSDN 中沒有良好的樣本此處There is a good sample in MSDN that shows how to use Ninject for dependency injection in an ASP.NET Web API project that you can download it from here.

所有的範例程式碼和程式碼片段會包含在 Web 研討會訓練套件,可在 https://go.microsoft.com/fwlink/?LinkID=248297&clcid=0x409 All sample code and snippets are included in the Web Camps Training Kit, available at https://go.microsoft.com/fwlink/?LinkID=248297&clcid=0x409.

目標Objectives

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

  • 實作 RESTful Web APIImplement a RESTful Web API
  • 從 HTML 用戶端呼叫 APICall the API from an HTML client

必要條件Prerequisites

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

安裝程式Setup

安裝程式碼片段Installing Code Snippets

為了方便起見,大部分的程式碼,您將沿著這個實驗室管理可從 Visual Studio 程式碼片段。For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. 若要安裝執行的程式碼片段 .\Source\Setup\CodeSnippets.vsi檔案。To install the code snippets run .\Source\Setup\CodeSnippets.vsi file.

如果您不熟悉 Visual Studio 程式碼片段,而且想要了解如何使用它們,您可以從這份文件參考附錄"附錄 a: 使用程式碼片段"。If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document "Appendix A: Using Code Snippets".

練習Exercises

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

  1. 練習 1: 建立唯讀的 Web APIExercise 1: Create a Read-Only Web API
  2. 練習 2: 建立讀取/寫入 Web APIExercise 2: Create a Read/Write Web API
  3. 練習 3: 使用從 HTML 用戶端的 Web APIExercise 3: Consume the Web API from an HTML Client

注意

每個練習會伴隨結束包含完成練習之後,您應該取得所產生的方案資料夾。Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. 如果您需要的所有練習所使用的其他說明,您可以使用此解決方案作為指南。You can use this solution as a guide if you need additional help working through the exercises.

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

練習 1: 建立唯讀的 Web APIExercise 1: Create a Read-Only Web API

在此練習中,您將連絡人的 manager 實作的唯寫的 GET 方法。In this exercise, you will implement the read-only GET methods for the contact manager.

工作 1-建立 API 專案Task 1 - Creating the API Project

在這個工作中,您將使用新的 ASP.NET web 專案範本建立 Web API 的 web 應用程式。In this task, you will use the new ASP.NET web project templates to create a Web API web application.

  1. 執行Visual Studio 2012 Express for Web,以前往開始然後輸入VS Express for Web然後按EnterRun Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter.

  2. 檔案功能表上,選取新的專案From the File menu, select New Project. 選取Visual C# |Web專案類型從 專案類型樹狀檢視中,然後選取ASP.NET MVC 4 Web 應用程式專案類型。Select the Visual C# | Web project type from the project type tree view, then select the ASP.NET MVC 4 Web Application project type. 將此專案的名稱ContactManager方案名稱開始,然後按一下 確定.Set the project's Name to ContactManager and the Solution name to Begin, then click OK.

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

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

  3. 在 ASP.NET MVC 4 專案的 [類型] 對話方塊中,選取Web API專案類型。In the ASP.NET MVC 4 project type dialog, select the Web API project type. 按一下 [確定 Deploying Office Solutions]。Click OK.

    指定的 Web API 專案型別Specifying the Web API project type

    指定 Web API 專案類型Specifying the Web API project type

工作 2-建立連絡人管理員 API 控制器Task 2 - Creating the Contact Manager API Controllers

在這個工作中,您將建立的 API 方法所在的控制器類別。In this task, you will create the controller classes in which API methods will reside.

  1. 刪除名為的檔案ValuesController.cs控制站從專案的資料夾。Delete the file named ValuesController.cs within Controllers folder from the project.

  2. 以滑鼠右鍵按一下控制器資料夾中的專案,然後選取新增 |控制器從內容功能表。Right-click the Controllers folder in the project and select Add | Controller from the context menu.

    將新的控制站新增至專案Adding a new controller to the project

    將新的控制站新增至專案Adding a new controller to the project

  3. 新增控制器出現對話方塊中,選取空白 API 控制器從 範本 功能表。In the Add Controller dialog that appears, select Empty API Controller from the Template menu. 將類別命名為控制器ContactControllerName the controller class ContactController. 然後,按一下 新增。Then, click Add.

    使用 [新增控制器] 對話方塊來建立新的 Web API 控制器Using the Add Controller dialog to create a new Web API controller

    使用 [新增控制器] 對話方塊來建立新的 Web API 控制器Using the Add Controller dialog to create a new Web API controller

  4. 將下列程式碼加入ContactControllerAdd the following code to the ContactController.

    (程式碼片段- Web API 實驗室-Ex01-Get API 方法)(Code Snippet - Web API Lab - Ex01 - Get API Method)

    public string[] Get()
    {
        return new string[]
        {
            "Hello",
            "World"
        };
    }
    
  5. 按下F5偵錯應用程式。Press F5 to debug the application. 預設的首頁上,為 Web API 專案應該會出現。The default home page for a Web API project should appear.

    ASP.NET Web API 應用程式的預設首頁The default home page of an ASP.NET Web API application

    ASP.NET Web API 應用程式的預設首頁The default home page of an ASP.NET Web API application

  6. 在 [Internet Explorer] 視窗中,按下F12鍵以開啟開發人員工具視窗。In the Internet Explorer window, press the F12 key to open the Developer Tools window. 按一下 網路索引標籤,然後再按一下開始擷取按鈕,開始擷取網路流量到視窗。Click the Network tab, and then click the Start Capturing button to begin capturing network traffic into the window.

    開啟 [網路] 索引標籤,然後啟動網路擷取Opening the network tab and initiating network capture

    開啟 [網路] 索引標籤,然後啟動網路擷取Opening the network tab and initiating network capture

  7. 附加與瀏覽器的網址列中的 URL /api/contact ,然後按 enter。Append the URL in the browser's address bar with /api/contact and press enter. 傳輸的詳細資料會出現在網路的 [擷取] 視窗中。The transmission details will appear in the network capture window. 請注意,回應的 MIME 類型,則application/jsonNote that the response's MIME type is application/json. 這示範了如何的預設輸出格式為 JSON。This demonstrates how the default output format is JSON.

    在 [網路] 檢視中檢視 Web API 要求的輸出Viewing the output of the Web API request in the Network view

    在 [網路] 檢視中檢視 Web API 要求的輸出Viewing the output of the Web API request in the Network view

    注意

    此時 Internet Explorer 10 的預設行為將會詢問使用者想要儲存或開啟 Web API 呼叫所產生的資料流。Internet Explorer 10's default behavior at this point will be to ask if the user would like to save or open the stream resulting from the Web API call. 輸出會包含 Web API URL 呼叫的 JSON 結果的文字檔。The output will be a text file containing the JSON result of the Web API URL call. 不要取消對話方塊,才能夠觀賞回應的內容,透過開發人員工具視窗。Do not cancel the dialog in order to be able to watch the response's content through Developers Tool window.

  8. 按一下 前往 詳細檢視以查看有關此 API 呼叫的回應詳細資料 按鈕。Click the Go to detailed view button to see more details about the response of this API call.

    切換至 詳細檢視Switch to Detailed View

    切換至 詳細檢視Switch to Detailed View

  9. 按一下 [回應主體若要檢視實際的 JSON 回應文字] 索引標籤。Click the Response body tab to view the actual JSON response text.

    檢視 JSON 輸出網路監視器中的文字Viewing the JSON output text in the network monitor

    在 網路監視器中檢視 JSON 輸出文字Viewing the JSON output text in the network monitor

工作 3-建立連絡人的模型,以及增強的連絡人的控制站Task 3 - Creating the Contact Models and Augment the Contact Controller

在這個工作中,您將建立的 API 方法所在的控制器類別。In this task, you will create the controller classes in which API methods will reside.

  1. 以滑鼠右鍵按一下模型資料夾,然後選取新增 |類別... 從內容功能表。Right-click the Models folder and select Add | Class... from the context menu.

    將新模型加入至 web 應用程式Adding a new model to the web application

    將新模型加入至 web 應用程式Adding a new model to the web application

  2. 在 [加入新項目] 對話方塊中,將新檔案命名Contact.cs按一下新增。In the Add New Item dialog, name the new file Contact.cs and click Add.

    建立新的連絡人類別檔案Creating the new Contact class file

    建立新的連絡人類別檔案Creating the new Contact class file

  3. 將下列反白顯示的程式碼,加入連絡人類別。Add the following highlighted code to the Contact class.

    (程式碼片段- Web API 實驗室-Ex01-連絡類別)(Code Snippet - Web API Lab - Ex01 - Contact Class)

    public class Contact
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    }
    
  4. ContactController類別中,選取 word字串方法定義中取得方法,並輸入文字連絡人In the ContactController class, select the word string in method definition of the Get method, and type the word Contact. 一旦這個字型別中,指標就會出現在單字開頭連絡人Once the word is typed in, an indicator will appear at the beginning of the word Contact. 請按住Ctrl鍵並按下句號 (.) 索引鍵或按一下圖示以開啟 設定在程式碼編輯器中,會自動填入的 協助 對話方塊中使用滑鼠使用模型指示詞命名空間。Either hold down the Ctrl key and press the period (.) key or click the icon using your mouse to open up the assistance dialog in the code editor, to automatically fill in the using directive for the Models namespace.

    為命名空間宣告中使用 Intellisense 協助

    為命名空間宣告中使用 Intellisense 協助Using Intellisense assistance for namespace declarations

  5. 修改程式碼取得方法,讓它傳回連絡人模型執行個體陣列。Modify the code for the Get method so that it returns an array of Contact model instances.

    (程式碼片段-傳回的連絡人清單 Web API 實驗室-Ex01-)(Code Snippet - Web API Lab - Ex01 - Returning a list of contacts)

    public Contact[] Get()
    {
        return new Contact[]
        {
            new Contact
            {
                Id = 1,
                Name = "Glenn Block"
            },
            new Contact
            {
                Id = 2,
                Name = "Dan Roth"
            }
        };
    }
    
  6. 按下F5偵錯 web 應用程式,在瀏覽器中的。Press F5 to debug the web application in the browser. 若要檢視對 API 的回應輸出的變更,請執行下列步驟。To view the changes made to the response output of the API, perform the following steps.

    1. 瀏覽器開啟後,請按下F12如果開發人員工具還不開啟。Once the browser opens, press F12 if the developer tools are not open yet.

    2. 按一下 [網路] 索引標籤。Click the Network tab.

    3. 按下開始擷取 按鈕。Press the Start Capturing button.

    4. 新增 URL 尾碼 /api/contact url 網址列,然後按下Enter索引鍵。Add the URL suffix /api/contact to the URL in the address bar and press the Enter key.

    5. 按下前往 [詳細檢視] 按鈕。Press the Go to detailed view button.

    6. 選取 [回應主體] 索引標籤。您應該會看到 JSON 字串,代表序列化的形式的連絡執行個體陣列。Select the Response body tab. You should see a JSON string representing the serialized form of an array of Contact instances.

      JSON 序列化的複雜的 Web API 方法呼叫的輸出JSON serialized output of a complex Web API method call

      複雜的 Web API 方法呼叫的序列化的 JSON 輸出JSON serialized output of a complex Web API method call

工作 4-解壓縮到服務層的功能Task 4 - Extracting Functionality into a Service Layer

這項工作中將示範如何擷取到的服務層,讓您輕鬆將其服務的功能分開控制站的圖層,藉此讓人重複使用之服務的實際執行工作的開發人員的功能。This task will demonstrate how to extract functionality into a Service layer to make it easy for developers to separate their service functionality from the controller layer, thereby allowing reusability of the services that actually do the work.

  1. 在方案根目錄中建立新的資料夾並將它命名ServicesCreate a new folder in the solution root and name it Services. 若要這樣做,請以滑鼠右鍵按一下ContactManager專案,然後選取新增 | 新資料夾,其命名服務To do this, right-click ContactManager project, select Add | New Folder, name it Services.

    建立服務 資料夾Creating Services folder

    建立服務 資料夾Creating Services folder

  2. 以滑鼠右鍵按一下Services資料夾,然後選取新增 |類別... 從內容功能表。Right-click the Services folder and select Add | Class... from the context menu.

    將新類別新增至 [服務] 資料夾Adding a new class to the Services folder

    將新類別新增至 [服務] 資料夾Adding a new class to the Services folder

  3. 加入新項目對話方塊隨即出現,新類別命名ContactRepository然後按一下新增When the Add New Item dialog appears, name the new class ContactRepository and click Add.

    建立類別檔案,以包含連絡人儲存機制的服務層的程式碼Creating a class file to contain the code for the Contact Repository service layer

    建立類別檔案,以包含連絡人儲存機制的服務層的程式碼Creating a class file to contain the code for the Contact Repository service layer

  4. 新增 using 指示詞ContactRepository.cs檔案,以包含模型命名空間。Add a using directive to the ContactRepository.cs file to include the models namespace.

    using ContactManager.Models;
    
  5. 將下列反白顯示的程式碼,加入ContactRepository.cs檔案以實作 GetAllContacts 方法。Add the following highlighted code to the ContactRepository.cs file to implement GetAllContacts method.

    (程式碼片段- Web API 實驗室-Ex01-連絡人儲存機制)(Code Snippet - Web API Lab - Ex01 - Contact Repository)

    public class ContactRepository
    {
        public Contact[] GetAllContacts()
        {
            return new Contact[]
            {
                new Contact
                {
                    Id = 1,
                    Name = "Glenn Block"
                },
                new Contact
                {
                    Id = 2,
                    Name = "Dan Roth"
                }
            };
        }
    }
    
  6. 開啟ContactController.cs檔案如果它尚未開啟。Open the ContactController.cs file if it is not already open.

  7. 新增下列 using 陳述式之檔案的命名空間宣告一節。Add the following using statement to the namespace declaration section of the file.

    using ContactManager.Services;
    
  8. 將下列反白顯示的程式碼,加入ContactController.cs新增私用欄位來代表儲存機制的執行個體,以便成員可以建立的類別的其餘部分使用的服務實作的類別。Add the following highlighted code to the ContactController.cs class to add a private field to represent the instance of the repository, so that the rest of the class members can make use of the service implementation.

    (程式碼片段-的 Web API 實驗室-Ex01-連絡人控制器)(Code Snippet - Web API Lab - Ex01 - Contact Controller)

    public class ContactController : ApiController
    {
        private ContactRepository contactRepository;
    
        public ContactController()
        {
            this.contactRepository = new ContactRepository();
        } 
        ...
    }
    
  9. 變更取得方法,讓它可讓使用連絡人儲存機制的服務。Change the Get method so that it makes use of the contact repository service.

    (程式碼片段-透過儲存機制中傳回的連絡人清單 Web API 實驗室-Ex01-)(Code Snippet - Web API Lab - Ex01 - Returning a list of contacts via the repository)

    public Contact[] Get()
    {
        return contactRepository.GetAllContacts();
    }
    
  10. 將中斷點放ContactController取得方法定義。Put a breakpoint on the ContactController's Get method definition.

將中斷點新增至連絡人控制器Adding breakpoints to the contact controller

將中斷點新增至連絡人控制器Adding breakpoints to the contact controller 11. F5 執行應用程式。Press F5 to run the application. 12. 當瀏覽器會開啟時,請按F12以開啟 開發人員工具。When the browser opens, press F12 to open the developer tools. 13. 按一下 [網路] 索引標籤。Click the Network tab. 14. 按一下 [開始擷取] 按鈕。Click the Start Capturing button. 15. 附加後置詞的 [網址] 列中的 URL /api/contact然後按Enter載入 API 控制器。Append the URL in the address bar with the suffix /api/contact and press Enter to load the API controller. 16. Visual Studio 2012 應該一次中斷取得方法開始執行。Visual Studio 2012 should break once Get method begins execution.

在 Get 方法中的重大Breaking within the Get method

在 Get 方法中的重大Breaking within the Get method 17. F5 繼續。Press F5 to continue. 18. 回到 Internet Explorer 如果它尚未在成為焦點。Go back to Internet Explorer if it is not already in focus. 請注意網路的 [擷取] 視窗。Note the network capture window.

<span data-ttu-id="e076d-255">![網路在 Internet Explorer 中顯示的 Web API 呼叫結果的檢視](build-restful-apis-with-aspnet-web-api/_static/image19.png "網路在 Internet Explorer 中顯示的 Web API 呼叫結果的檢視")</span><span class="sxs-lookup"><span data-stu-id="e076d-255">![Network view in Internet Explorer showing results of the Web API call](build-restful-apis-with-aspnet-web-api/_static/image19.png "Network view in Internet Explorer showing results of the Web API call")</span></span>

<span data-ttu-id="e076d-256">*在 Internet Explorer 中顯示的 Web API 呼叫結果的 [網路] 檢視*</span><span class="sxs-lookup"><span data-stu-id="e076d-256">*Network view in Internet Explorer showing results of the Web API call*</span></span>
  1. 按一下 前往 詳細檢視 按鈕。Click the Go to detailed view button.

  2. 按一下 [回應主體] 索引標籤。請注意 JSON 輸出的 API,以及它如何表示兩個服務層所擷取的連絡人。Click the Response body tab. Note the JSON output of the API call, and how it represents the two contacts retrieved by the service layer.

    開發人員工具 視窗中檢視 Web API 的 JSON 輸出Viewing the JSON output from the Web API in the developer tools window

    開發人員工具 視窗中檢視 Web API 的 JSON 輸出Viewing the JSON output from the Web API in the developer tools window

練習 2: 建立讀取/寫入 Web APIExercise 2: Create a Read/Write Web API

在此練習中,您會將實作 POST 和 PUT 方法的連絡人管理員 」 來啟用資料編輯功能。In this exercise, you will implement POST and PUT methods for the contact manager to enable it with data-editing features.

工作 1-開啟 Web API 專案Task 1 - Opening the Web API Project

在這個工作中,您會準備增強,因此可以接受使用者輸入,在練習 1 中建立的 Web API 專案。In this task, you will prepare to enhance the Web API project created in Exercise 1 so that it can accept user input.

  1. 執行Visual Studio 2012 Express for Web,以前往開始然後輸入VS Express for Web然後按EnterRun Visual Studio 2012 Express for Web, to do this go to Start and type VS Express for Web then press Enter.

  2. 開啟開始解決方案位於來源/Ex02-ReadWriteWebAPI/開始/ 資料夾。Open the Begin solution located at Source/Ex02-ReadWriteWebAPI/Begin/ folder. 否則,您可能會繼續使用結束方案取得完成前一個練習。Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. 如果您開啟提供開始解決方案中,您必須下載某些缺少的 NuGet 封裝才能繼續。If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. 若要這樣做,請按一下專案功能表,然後選取管理 NuGet 套件To do this, click the Project menu and select Manage NuGet Packages.

    2. 在 [管理 NuGet 套件] 對話方塊中,按一下還原才能下載遺漏的套件。In the Manage NuGet Packages dialog, click Restore in order to download missing packages.

    3. 最後,按一下 建置方案建置 | 建置方案Finally, build the solution by clicking Build | Build Solution.

      注意

      使用 NuGet 的優點之一是,您不需要寄送您的專案中的所有程式庫專案縮小。One of the advantages of using NuGet is that you don't have to ship all the libraries in your project, reducing the project size. NuGet Power tools,藉由指定封裝版本在 Packages.config 檔案中,您將能夠下載所有必要的程式庫第一次執行專案。With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. 這就是為什麼您必須在您開啟現有的方案從這個實驗室之後,執行這些步驟。This is why you will have to run these steps after you open an existing solution from this lab.

  3. 開啟Services/ContactRepository.cs檔案。Open the Services/ContactRepository.cs file.

工作 2-加入連絡人儲存機制實作的資料持續性功能Task 2 - Adding Data-Persistence Features to the Contact Repository Implementation

在這個工作中,您將會擴大 ContactRepository 的類別,使其可以保存,並接受使用者輸入和新的連絡人執行個體,在練習 1 中建立的 Web API 專案。In this task, you will augment the ContactRepository class of the Web API project created in Exercise 1 so that it can persist and accept user input and new Contact instances.

  1. 新增下列常數ContactRepository類別來代表 web 伺服器快取項目索引鍵名稱的稍後在本練習中的名稱。Add the following constant to the ContactRepository class to represent the name of the web server cache item key name later in this exercise.

    private const string CacheKey = "ContactStore";
    
  2. 新增的建構函式ContactRepository包含下列程式碼。Add a constructor to the ContactRepository containing the following code.

    (程式碼片段- Web API 實驗室-Ex02-連絡人儲存機制的建構函式)(Code Snippet - Web API Lab - Ex02 - Contact Repository Constructor)

    public ContactRepository()
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
            if (ctx.Cache[CacheKey] == null)
            {
                var contacts = new Contact[]
                {
                    new Contact
                    {
                        Id = 1, Name = "Glenn Block"
                    },
                    new Contact
                    {
                        Id = 2, Name = "Dan Roth"
                    }
                };
    
                ctx.Cache[CacheKey] = contacts;
            }
        }
    }
    
  3. 修改程式碼GetAllContacts方法如下所示。Modify the code for the GetAllContacts method as demonstrated below.

    (程式碼片段- Web API 實驗室-Ex02-取得所有連絡人)(Code Snippet - Web API Lab - Ex02 - Get All Contacts)

    public Contact[] GetAllContacts()
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
            return (Contact[])ctx.Cache[CacheKey];
        }
    
        return new Contact[]
            {
                new Contact
                {
                    Id = 0,
                    Name = "Placeholder"
                }
            };
    }
    

    注意

    這個範例是供示範之用,並將 web 伺服器的快取做為儲存媒體,以便值將同時適用於多個用戶端,而不是使用工作階段儲存機制或要求儲存體的存留期。This example is for demonstration purposes and will use the web server's cache as a storage medium, so that the values will be available to multiple clients simultaneously, rather than use a Session storage mechanism or a Request storage lifetime. 可以使用 Entity Framework、 XML 儲存體或任何其他各種取代 web 伺服器快取。One could use Entity Framework, XML storage, or any other variety in place of the web server cache.

  4. 實作一個名為的新方法SaveContactContactRepository類別來儲存連絡人的工作。Implement a new method named SaveContact to the ContactRepository class to do the work of saving a contact. SaveContact方法應該採用單一連絡人參數和傳回布林值,指出成功或失敗。The SaveContact method should take a single Contact parameter and return a Boolean value indicating success or failure.

    (程式碼片段- Web API 的實驗室-Ex02-實作 SaveContact 方法)(Code Snippet - Web API Lab - Ex02 - Implementing the SaveContact Method)

    public bool SaveContact(Contact contact)
    {
        var ctx = HttpContext.Current;
    
        if (ctx != null)
        {
             try
             {
                  var currentData = ((Contact[])ctx.Cache[CacheKey]).ToList();
                  currentData.Add(contact);
                  ctx.Cache[CacheKey] = currentData.ToArray();
    
                  return true;
             }
             catch (Exception ex)
             {
                  Console.WriteLine(ex.ToString());
                  return false;
             }
        }
    
        return false;
    }
    

練習 3: 使用從 HTML 用戶端的 Web APIExercise 3: Consume the Web API from an HTML Client

在此練習中,您將建立 HTML 用戶端呼叫 Web API。In this exercise, you will create an HTML client to call the Web API. 此用戶端會使用 JavaScript 的 Web api 方便資料交換,並將結果顯示在網頁瀏覽器使用 HTML 標記。This client will facilitate data exchange with the Web API using JavaScript and will display the results in a web browser using HTML markup.

工作 1-修改 [索引] 檢視,以提供 GUI 顯示連絡人Task 1 - Modifying the Index View to Provide a GUI for Displaying Contacts

在這個工作中,您將修改以支援的需求在 HTML 瀏覽器中顯示現有的連絡人清單 web 應用程式的預設索引檢視。In this task, you will modify the default Index view of the web application to support the requirement of displaying the list of existing contacts in an HTML browser.

  1. 開啟Visual Studio 2012 Express for Web如果它尚未開啟。Open Visual Studio 2012 Express for Web if it is not already open.

  2. 開啟開始解決方案位於來源/Ex03-ConsumingWebAPI/開始/ 資料夾。Open the Begin solution located at Source/Ex03-ConsumingWebAPI/Begin/ folder. 否則,您可能會繼續使用結束方案取得完成前一個練習。Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. 如果您開啟提供開始解決方案中,您必須下載某些缺少的 NuGet 封裝才能繼續。If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. 若要這樣做,請按一下專案功能表,然後選取管理 NuGet 套件To do this, click the Project menu and select Manage NuGet Packages.

    2. 在 [管理 NuGet 套件] 對話方塊中,按一下還原才能下載遺漏的套件。In the Manage NuGet Packages dialog, click Restore in order to download missing packages.

    3. 最後,按一下 建置方案建置 | 建置方案Finally, build the solution by clicking Build | Build Solution.

      注意

      使用 NuGet 的優點之一是,您不需要寄送您的專案中的所有程式庫專案縮小。One of the advantages of using NuGet is that you don't have to ship all the libraries in your project, reducing the project size. NuGet Power tools,藉由指定封裝版本在 Packages.config 檔案中,您將能夠下載所有必要的程式庫第一次執行專案。With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. 這就是為什麼您必須在您開啟現有的方案從這個實驗室之後,執行這些步驟。This is why you will have to run these steps after you open an existing solution from this lab.

  3. 開啟Index.cshtml位於檔案Views/Home資料夾。Open the Index.cshtml file located at Views/Home folder.

  4. Div 項目內的 HTML 程式碼取代識別碼主體使它看起來像下列程式碼。Replace the HTML code within the div element with id body so that it looks like the following code.

    <div id="body">
        <ul id="contacts"></ul>
    </div>
    
  5. 要執行 Web API 的 HTTP 要求之檔案的底部新增下列 Javascript 程式碼。Add the following Javascript code at the bottom of the file to perform the HTTP request to the Web API.

    @section scripts{
    <script type="text/javascript">
    $(function()
    {
            $.getJSON('/api/contact', function(contactsJsonPayload)
            {
                $(contactsJsonPayload).each(function(i, item)
                {
                    $('#contacts').append('<li>' + item.Name + '</li>');
                });
            });
    });
    </script>
    }
    
  6. 開啟ContactController.cs檔案如果它尚未開啟。Open the ContactController.cs file if it is not already open.

  7. 將中斷點放在取得方法ContactController類別。Place a breakpoint on the Get method of the ContactController class.

    在 API 控制器的 Get 方法中放置中斷點Placing a breakpoint on the Get method of the API controller

    將中斷點放上 API 控制器的 Get 方法Placing a breakpoint on the Get method of the API controller

  8. 按下F5執行專案。Press F5 to run the project. HTML 文件時,會載入瀏覽器。The browser will load the HTML document.

    注意

    請確定您正在瀏覽至您的應用程式的根目錄 URL。Ensure that you are browsing to the root URL of your application.

  9. 一旦頁面載入和執行的 JavaScript,會叫用中斷點,並執行程式碼,將會暫停在控制器中。Once the page loads and the JavaScript executes, the breakpoint will be hit and the code execution will pause in the controller.

    使用 VS Express for Web 的 Web API 呼叫偵錯Debugging into the Web API calls using VS Express for Web

    偵錯使用 Visual Studio 2012 Express for Web 的 Web API 呼叫Debugging into the Web API call using Visual Studio 2012 Express for Web

  10. 移除中斷點,然後按F5或偵錯工具列繼續按鈕以繼續載入瀏覽器中的檢視。Remove the breakpoint and press F5 or the debugging toolbar's Continue button to continue loading the view in the browser. Web API 呼叫完成之後應該會看到呼叫瀏覽器中的 顯示為清單項目從 Web API 傳回的連絡人。Once the Web API call completes you should see the contacts returned from the Web API call displayed as list items in the browser.

    在瀏覽器中顯示為清單項目 API 呼叫的結果Results of the API call displayed in the browser as list items

    在瀏覽器中顯示為清單項目 API 呼叫的結果Results of the API call displayed in the browser as list items

  11. 停止偵錯。Stop debugging.

工作 2-修改 [索引] 檢視,以提供 GUI 建立連絡人Task 2 - Modifying the Index View to Provide a GUI for Creating Contacts

在這個工作中,您將繼續修改索引檢視的 MVC 應用程式。In this task, you will continue to modify the Index view of the MVC application. 表單會新增至 HTML 頁面,將會擷取使用者輸入,並將它傳送給 Web API 來建立新的連絡人,並將建立新的 Web API 控制器方法,以收集從 GUI 的日期。A form will be added to the HTML page that will capture user input and send it to the Web API to create a new Contact, and a new Web API controller method will be created to collect date from the GUI.

  1. 開啟ContactController.cs檔案。Open the ContactController.cs file.

  2. 新增至名為控制器類別的新方法Post如下列程式碼所示。Add a new method to the controller class named Post as shown in the following code.

    (程式碼片段- Web API 實驗室-Ex03-Post 方法)(Code Snippet - Web API Lab - Ex03 - Post Method)

    public HttpResponseMessage Post(Contact contact)
    {
        this.contactRepository.SaveContact(contact);
    
        var response = Request.CreateResponse<Contact>(System.Net.HttpStatusCode.Created, contact);
    
        return response;
    }
    
  3. 開啟Index.cshtml檔案在 Visual Studio 中,如果它尚未開啟。Open the Index.cshtml file in Visual Studio if it is not already open.

  4. 將下列 HTML 程式碼加入檔案之後您加入在先前的工作的未排序清單。Add the HTML code below to the file just after the unordered list you added in the previous task.

    <form id="saveContactForm" method="post">
    <h3>Create a new Contact</h3>
    <p>
        <label for="contactId">Contact Id:</label>
        <input type="text" name="Id" />
    </p>
    <p>
        <label for="contactName">Contact Name:</label>
        <input type="text" name="Name" />
    </p>
    <input type="button" id="saveContact" value="Save" />
    </form>
    
  5. 在底部的 文件的指令碼項目,新增下列醒目提示的程式碼,來處理按鈕 click 事件,將資料張貼至 Web API 使用 HTTP POST 呼叫。Within the script element at the bottom of the document, add the following highlighted code to handle button-click events, which will post the data to the Web API using an HTTP POST call.

    <script type="text/javascript">
    ... 
    $('#saveContact').click(function()
             {
                  $.post("api/contact",
                        $("#saveContactForm").serialize(),
                        function(value)
                        {
                             $('#contacts').append('<li>' + value.Name + '</li>');
                        },
                        "json"
                  );
             });
    </script>
    
  6. ContactController.cs,將中斷點放上Post方法。In ContactController.cs, place a breakpoint on the Post method.

  7. 按下F5瀏覽器中執行應用程式。Press F5 to run the application in the browser.

  8. 一旦頁面載入瀏覽器中,輸入新的連絡人名稱和識別碼,然後按一下儲存 按鈕。Once the page is loaded in the browser, type in a new contact name and Id and click the Save button.

    用戶端 HTML 文件載入瀏覽器The client HTML document loaded in the browser

    用戶端 HTML 文件載入瀏覽器The client HTML document loaded in the browser

  9. 當偵錯工具視窗會在中斷Post方法,可看一下屬性連絡參數。When the debugger window breaks in the Post method, take a look at the properties of the contact parameter. 值應該符合您在表單中輸入的資料。The values should match the data you entered in the form.

    從用戶端傳送至 Web API 的連絡人物件The Contact object being sent to the Web API from the client

    從用戶端傳送至 Web API 的連絡人物件The Contact object being sent to the Web API from the client

  10. 逐步執行直到偵錯工具中的方法回應在建立變數。Step through the method in the debugger until the response variable has been created. 中的檢查時區域變數偵錯工具 視窗中的,您會看到已設定的所有屬性。Upon inspection in the Locals window in the debugger, you'll see that all the properties have been set.

在 偵錯工具中建立的回應The response following creation in the debugger

在偵錯工具中建立的回應The response following creation in the debugger 11. 如果您按下F5或按繼續在偵錯工具將完成的要求。If you press F5 or click Continue in the debugger the request will complete. 所儲存的連絡人清單一旦您切換回瀏覽器,已加入新的連絡人ContactRepository實作。Once you switch back to the browser, the new contact has been added to the list of contacts stored by the ContactRepository implementation.

瀏覽器會反映成功建立新的連絡人執行個體The browser reflects successful creation of the new contact instance

瀏覽器會反映成功建立新的連絡人執行個體The browser reflects successful creation of the new contact instance

注意

此外,您可以在其中部署此應用程式至 Azure 的下列附錄 c: 發佈 ASP.NET MVC 4 應用程式使用 Web DeployAdditionally, you can deploy this application to Azure following Appendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy.


總結Summary

這個實驗室已引進新的 ASP.NET Web API 架構,並使用架構的 RESTful Web Api 的實作。This lab has introduced you to the new ASP.NET Web API framework and to the implementation of RESTful Web APIs using the framework. 從這裡開始,您可以建立新的存放庫,可協助資料持續性使用任意數目的機制,並連接該服務而不是提供做為範例,在這個實驗室中其中一個。From here, you could create a new repository that facilitates data persistence using any number of mechanisms and wire that service up rather than the simple one provided as an example in this lab. Web API 支援一些其他功能,例如啟用支援 HTTP 和 JSON 或 XML 的任何語言撰寫的非 HTML 用戶端傳來的通訊。Web API supports a number of additional features, such as enabling communication from non-HTML clients written in any language that supports HTTP and JSON or XML. 裝載 Web API,典型的 web 應用程式之外的能力也是可行的以及已建立您自己的序列化格式的能力。The ability to host a Web API outside of a typical web application is also possible, as well as is the ability to create your own serialization formats.

ASP.NET 網站有一個專門用來在 ASP.NET Web API 架構的區域[ https://asp.net/web-api ](https://asp.net/web-api)。The ASP.NET Web site has an area dedicated to the ASP.NET Web API framework at [https://asp.net/web-api](https://asp.net/web-api). 此站台將持續提供最新的資訊、 範例和新聞與 Web API,因此請經常如果您想要更深入地鑽研建立給幾乎任何裝置或開發架構,可用的自訂 Web Api 的圖案。This site will continue to provide late-breaking information, samples, and news related to Web API, so check it frequently if you'd like to delve deeper into the art of creating custom Web APIs available to virtually any device or development framework.

附錄 a: 使用程式碼片段Appendix A: Using Code Snippets

使用程式碼片段,您會有您需要在隨手可得的所有程式碼。With code snippets, you have all the code you need at your fingertips. 實驗室課程文件會告訴您完全時您可以使用它們,如下圖所示。The lab document will tell you exactly when you can use them, as shown in the following figure.

若要將程式碼插入您的專案使用 Visual Studio 程式碼片段Using Visual Studio code snippets to insert code into your project

若要將程式碼插入您的專案使用 Visual Studio 程式碼片段Using Visual Studio code snippets to insert code into your project

若要新增的程式碼片段,使用鍵盤 (僅限 C#)To add a code snippet using the keyboard (C# only)

  1. 將游標放在您想要插入的程式碼。Place the cursor where you would like to insert the code.

  2. 開始輸入程式碼片段名稱 (不含空格或連字號)。Start typing the snippet name (without spaces or hyphens).

  3. 觀看為 IntelliSense 會顯示相符的程式碼片段的名稱。Watch as IntelliSense displays matching snippets' names.

  4. 選取正確的程式碼片段 (或直到選取整個程式碼片段名稱時,保留 輸入)。Select the correct snippet (or keep typing until the entire snippet's name is selected).

  5. 按下 Tab 鍵兩次的游標位置插入程式碼片段。Press the Tab key twice to insert the snippet at the cursor location.

    開始鍵入程式碼片段名稱Start typing the snippet name

    開始鍵入程式碼片段名稱Start typing the snippet name

    按 Tab 鍵以選取反白顯示的程式碼片段Press Tab to select the highlighted snippet

    按 Tab 鍵以選取反白顯示的程式碼片段Press Tab to select the highlighted snippet

    再次按 Tab 鍵和程式碼片段會依序展開Press Tab again and the snippet will expand

    再次按 Tab 鍵和程式碼片段會展開Press Tab again and the snippet will expand

若要新增的程式碼片段,使用滑鼠 (C#、 Visual Basic 和 XML)To add a code snippet using the mouse (C#, Visual Basic and XML)

  1. 以滑鼠右鍵按一下您要插入程式碼片段。Right-click where you want to insert the code snippet.

  2. 選取 插入程式碼片段後面My Code SnippetsSelect Insert Snippet followed by My Code Snippets.

  3. 選擇相關的程式片段,從清單中,對它按一下。Pick the relevant snippet from the list, by clicking on it.

    以滑鼠右鍵按一下您要插入程式碼片段,然後選取 插入程式碼片段Right-click where you want to insert the code snippet and select Insert Snippet

    以滑鼠右鍵按一下您要插入程式碼片段,然後選取 插入程式碼片段Right-click where you want to insert the code snippet and select Insert Snippet

    對它按一下挑選清單中,相關程式碼片段Pick the relevant snippet from the list, by clicking on it

    對它按一下挑選清單中,相關程式碼片段Pick the relevant snippet from the list, by clicking on it

附錄 b: 安裝 Visual Studio Express 2012 for WebAppendix B: Installing Visual Studio Express 2012 for Web

您可以安裝Microsoft Visual Studio Express 2012 for Web或另一個"Express"使用版本**Microsoft Web Platform Installer**.You can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. 下列指示會引導您完成安裝所需的步驟Visual studio Express 2012 for Web使用Microsoft Web Platform InstallerThe following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.

  1. 移至[ https://go.microsoft.com/?linkid=9810169 ](https://go.microsoft.com/?linkid=9810169)。Go to [https://go.microsoft.com/?linkid=9810169](https://go.microsoft.com/?linkid=9810169). 或者,如果您已安裝 Web Platform Installer,您可以開啟它,並搜尋產品" Visual Studio Express 2012 for Web 含 Azure SDK"。Alternatively, if you already have installed Web Platform Installer, you can open it and search for the product "Visual Studio Express 2012 for Web with Azure SDK".

  2. 按一下 立即安裝Click on Install Now. 如果您不需要Web Platform Installer您將會重新導向至下載並安裝第一次。If you do not have Web Platform Installer you will be redirected to download and install it first.

  3. 一次Web Platform Installer已開啟,按一下安裝,啟動安裝程式。Once Web Platform Installer is open, click Install to start the setup.

    安裝 Visual Studio ExpressInstall Visual Studio Express

    安裝 Visual Studio ExpressInstall Visual Studio Express

  4. 閱讀所有產品的授權和詞彙,然後按一下我接受以繼續。Read all the products' licenses and terms and click I Accept to continue.

    接受授權條款

    接受授權條款Accepting the license terms

  5. 等候完成的下載與安裝程序。Wait until the downloading and installation process completes.

    安裝進度

    安裝進度Installation progress

  6. 安裝完成時,按一下完成When the installation completes, click Finish.

    安裝已完成

    安裝已完成Installation completed

  7. 按一下 結束關閉 Web Platform Installer。Click Exit to close Web Platform Installer.

  8. 若要開啟 Visual Studio Express for Web,請前往開始畫面,即可開始撰寫" VS Express",然後按一下VS Express for Web圖格。To open Visual Studio Express for Web, go to the Start screen and start writing "VS Express", then click on the VS Express for Web tile.

    VS Express for Web 圖格

    VS Express for Web 圖格VS Express for Web tile

附錄 c: 發佈 ASP.NET MVC 4 應用程式使用 Web DeployAppendix C: Publishing an ASP.NET MVC 4 Application using Web Deploy

本附錄將說明如何從 Azure 入口網站中建立新的網站和發行您取得所遵循的實驗室中,利用 Web Deploy 發行所提供的功能由 Azure 應用程式。This appendix will show you how to create a new web site from the Azure Portal and publish the application you obtained by following the lab, taking advantage of the Web Deploy publishing feature provided by Azure.

工作 1: 從 Azure 入口網站中建立新的網站Task 1 - Creating a New Web Site from the Azure Portal

  1. 移至Azure 管理入口網站並使用您的訂用帳戶相關聯的 Microsoft 認證登入。Go to the Azure Management Portal and sign in using the Microsoft credentials associated with your subscription.

    注意

    使用 Azure,您可以免費託管 10 個 ASP.NET 網站,並再隨著流量成長而調整。With Azure you can host 10 ASP.NET Web Sites for free and then scale as your traffic grows. 您可以註冊申請此處You can sign up here.

    登入 Windows Azure 入口網站Log on to Windows Azure portal

    登入入口網站Log on to Portal

  2. 按一下 新增命令列上。Click New on the command bar.

    建立新的 Web 站台Creating a new Web Site

    建立新的網站Creating a new Web Site

  3. 按一下 計算 | 網站Click Compute | Web Site. 然後選取快速建立選項。Then select Quick Create option. 新的網站提供可用的 URL,然後按建立網站Provide an available URL for the new web site and click Create Web Site.

    注意

    Azure 是您可以控制和管理雲端中執行的 web 應用程式的主應用程式。Azure is the host for a web application running in the cloud that you can control and manage. [快速建立] 選項可讓您從 azure 入口網站外部的已完成的 web 應用程式部署。The Quick Create option allows you to deploy a completed web application to the Azure from outside the portal. 它不包含設定資料庫的步驟。It does not include steps for setting up a database.

    建立新的網站上,使用 快速建立Creating a new Web Site using Quick Create

    建立新的網站上,使用 快速建立Creating a new Web Site using Quick Create

  4. 等到新網站建立。Wait until the new Web Site is created.

  5. 建立網站後按一下底下的連結URL資料行。Once the Web Site is created click the link under the URL column. 檢查新的網站運作。Check that the new Web Site is working.

    瀏覽至新的 web 站台Browsing to the new web site

    瀏覽至新的網站Browsing to the new web site

    執行的 web 站台Web site running

    執行的網站Web site running

  6. 返回入口網站並按一下底下的網站名稱名稱資料行來顯示 [管理] 頁面。Go back to the portal and click the name of the web site under the Name column to display the management pages.

    開啟 網站管理頁面Opening the web site management pages

    開啟 網站管理頁面Opening the Web Site management pages

  7. 儀表板頁面的 快速概覽區段中,按一下下載發行設定檔連結。In the Dashboard page, under the quick glance section, click the Download publish profile link.

    注意

    發行設定檔包含所有發行至 Azure,以針對每個已啟用的發行方法的 web 應用程式所需的資訊。The publish profile contains all of the information required to publish a web application to a Azure for each enabled publication method. 發行設定檔包含 Url、 使用者認證和連接到並對每個發行集的方法已啟用的端點進行驗證所需的資料庫字串。The publish profile contains the URLs, user credentials and database strings required to connect to and authenticate against each of the endpoints for which a publication method is enabled. Microsoft WebMatrix 2Microsoft Visual Studio Express for WebMicrosoft Visual Studio 2012支援讀取發行設定檔,以自動化的這些程式的組態正在發行至 Azure web 應用程式。Microsoft WebMatrix 2, Microsoft Visual Studio Express for Web and Microsoft Visual Studio 2012 support reading publish profiles to automate configuration of these programs for publishing web applications to Azure.

    正在下載網站發行設定檔Downloading the web site publish profile

    正在下載網站發行設定檔Downloading the Web Site publish profile

  8. 下載發行設定檔至已知位置。Download the publish profile file to a known location. 進一步在這個練習中,您會看到如何使用此檔案來發佈 Azure web 應用程式從 Visual Studio。Further in this exercise you will see how to use this file to publish a web application to Azure from Visual Studio.

    儲存發行設定檔Saving the publish profile file

    儲存發行設定檔Saving the publish profile file

工作 2-設定資料庫伺服器Task 2 - Configuring the Database Server

如果您的應用程式會使用 SQL Server 資料庫,您必須建立 SQL Database 伺服器。If your application makes use of SQL Server databases you will need to create a SQL Database server. 如果您想要部署簡單的應用程式不會使用 SQL Server,您可能會略過這項工作。If you want to deploy a simple application that does not use SQL Server you might skip this task.

  1. 您將需要 SQL Database 伺服器來儲存應用程式資料庫。You will need a SQL Database server for storing the application database. 您可以從您的訂用帳戶,在 Azure 管理入口網站中檢視 SQL Database 伺服器Sql Database | 伺服器 | 伺服器的儀表板.You can view the SQL Database servers from your subscription in the Azure Management portal at Sql Databases | Servers | Server's Dashboard. 如果您沒有建立伺服器,您可以建立一個使用新增命令列上的按鈕。If you do not have a server created, you can create one using the Add button on the command bar. 請記下的伺服器名稱和 URL、 系統管理員身分登入名稱和密碼,如同您會在下一個工作中使用它們。Take note of the server name and URL, administrator login name and password, as you will use them in the next tasks. 並未建立資料庫,因為它會建立在稍後的階段。Do not create the database yet, as it will be created in a later stage.

    SQL Database 伺服器儀表板SQL Database Server Dashboard

    SQL Database 伺服器儀表板SQL Database Server Dashboard

  2. 下一個工作在您將測試資料庫連接,從 Visual Studio 中,因此您需要在伺服器的清單包含您的本機 IP 位址允許的 IP 位址In the next task you will test the database connection from Visual Studio, for that reason you need to include your local IP address in the server's list of Allowed IP Addresses. 若要這樣做,請按一下設定,選取的 IP 位址目前的用戶端 IP 位址並將它貼上起始 IP 位址結束 IP 位址文字方塊中,然後按一下 [ add-client-ip-address-ok-button ] 按鈕。To do that, click Configure, select the IP address from Current Client IP Address and paste it on the Start IP Address and End IP Address text boxes and click the add-client-ip-address-ok-button button.

    新增用戶端 IP 位址

    新增用戶端 IP 位址Adding Client IP Address

  3. 一次用戶端 IP 位址新增至允許的 IP 位址清單中,按一下儲存來確認變更。Once the Client IP Address is added to the allowed IP addresses list, click on Save to confirm the changes.

    確認變更

    確認變更Confirm Changes

工作 3-發行 ASP.NET MVC 4 應用程式使用 Web DeployTask 3 - Publishing an ASP.NET MVC 4 Application using Web Deploy

  1. 返回至 ASP.NET MVC 4 的方案。Go back to the ASP.NET MVC 4 solution. 方案總管,以滑鼠右鍵按一下網站專案,然後選取發佈In the Solution Explorer, right-click the web site project and select Publish.

    發行應用程式Publishing the Application

    發行網站Publishing the web site

  2. 匯入發行設定檔儲存在第一項工作。Import the publish profile you saved in the first task.

    匯入發行設定檔Importing the publish profile

    匯入發行設定檔Importing publish profile

  3. 按一下 驗證連線Click Validate Connection. 驗證完成後按一下下一步Once Validation is complete click Next.

    注意

    一旦您看到 [驗證連線] 按鈕旁邊會出現綠色核取記號完成驗證。Validation is complete once you see a green checkmark appear next to the Validate Connection button.

    驗證連接Validating connection

    驗證連接Validating connection

  4. 設定頁面的 資料庫區段中,按一下您的資料庫連接文字方塊旁邊的按鈕 (也就是DefaultConnection)。In the Settings page, under the Databases section, click the button next to your database connection's textbox (i.e. DefaultConnection).

    Web 部署組態Web deploy configuration

    Web 部署設定Web deploy configuration

  5. 設定資料庫連線,如下所示:Configure the database connection as follows:

    • 伺服器名稱輸入您使用 SQL Database 伺服器的 URL tcp: 前置詞。In the Server name type your SQL Database server URL using the tcp: prefix.

    • 使用者名輸入您的伺服器系統管理員身分登入名稱。In User name type your server administrator login name.

    • 密碼輸入您的伺服器系統管理員身分登入密碼。In Password type your server administrator login password.

    • 輸入新的資料庫名稱,例如: MVC4SampleDBType a new database name, for example: MVC4SampleDB.

      設定目的地連接字串Configuring destination connection string

      設定目的地連接字串Configuring destination connection string

  6. 然後按一下 [確定]。 Then click OK. 當系統提示您建立資料庫時,按一下When prompted to create the database click Yes.

    建立資料庫Creating the database

    建立資料庫Creating the database

  7. 您將用來連接至 Windows Azure 中的 SQL 資料庫的連接字串會顯示在文字方塊中的預設連線。The connection string you will use to connect to SQL Database in Windows Azure is shown within Default Connection textbox. 然後按 [下一步] 。Then click Next.

    連接字串指向 SQL DatabaseConnection string pointing to SQL Database

    連接字串指向 SQL DatabaseConnection string pointing to SQL Database

  8. Preview頁面上,按一下發佈In the Preview page, click Publish.

    Web 應用程式發行Publishing the web application

    發行 web 應用程式Publishing the web application

  9. 當發行程序完成時,預設瀏覽器會開啟已發行的網站。Once the publishing process finishes, your default browser will open the published web site.

    應用程式發行至 Windows AzureApplication published to Windows Azure

    應用程式發佈至 AzureApplication published to Azure