使用ASP.NET Web API構建RESTful API

蔡俊鋒發表於2017-11-01
 近年來,很明顯,HTTP不僅僅是為了提供HTML頁面。它也是構建Web API的強大平臺,使用少量動詞(GET,POST等)加上一些簡單的概念,如URI和標頭檔案。ASP.NET Web API是一組簡化HTTP程式設計的元件。因為它構建在ASP.NET MVC執行時之上,Web API自動處理HTTP的低階傳輸細節。同時,Web API自然地暴露了HTTP程式設計模型。事實上,Web API的一個目標是不要抽象出HTTP的現實。因此,Web API既靈活又易於擴充套件。在這個動手實驗中,您將使用Web API為聯絡人管理器應用程式構建一個簡單的REST API。您還將構建一個客戶端來使用API。REST架構風格已被證明是利用HTTP的有效方法 - 儘管它當然不是唯一有效的HTTP方法。聯絡人經理將公開RESTful列表,新增和刪除聯絡人等。此實驗室需要對HTTP,REST的基本瞭解,並假設您具有HTML,JavaScript和jQuery的基本工作知識。
注意
ASP.NET網站在[https://asp.net/web-api](https://asp.net/web-api)上專用於ASP.NET Web API框架)。該網站將繼續提供與Web API相關的最新資訊,示例和新聞,如果您想深入瞭解建立可用於任何裝置或開發框架的自定義Web API的技術,請經常檢查。
與ASP.NET MVC 4類似的ASP.NET Web API在將服務層與控制器分離方面具有很大的靈活性,允許您很容易地使用幾個可用的依賴注入框架。在MSDN中有一個很好的示例,顯示瞭如何在ASP.NET Web API專案中使用Ninject進行依賴注入,您可以從這裡下載它。
所有示例程式碼和程式碼段都包含在Web Camps培訓工具包中,可從https://go.microsoft.com/fwlink/?LinkID=248297&clcid=0x409獲取。
目標


在這個動手實驗中,您將學習如何:
實現RESTful Web API
從HTML客戶端呼叫API
先決條件


完成此動手實驗室需要以下內容:
適用於Web或上級的Microsoft Visual Studio Express 2012(有關如何安裝的說明,請參閱附錄B)。
建立


安裝程式碼片段
為方便起見,您將在本實驗中管理的大部分程式碼可用作Visual Studio程式碼片段。要安裝程式碼片段執行。\ Source \ Setup \ CodeSnippets.vsi檔案。
如果您不熟悉Visual Studio程式碼片段,並想了解如何使用它們,可以參考本文件“ 附錄A:使用程式碼段 ”中的附錄。
演習
這個動手實驗室包括以下練習:
練習1:建立只讀Web API
練習2:建立一個讀/寫Web API
練習3:從HTML客戶端使用Web API
注意
每個練習都附帶一個End資料夾,其中包含您在完成練習後應獲得的最終解決方案。如果您需要額外的幫助,您可以使用此解決方案作為指導。
預計完成本實驗的時間:60分鐘。
練習1:建立只讀Web API


在本練習中,您將為聯絡人管理器實現只讀GET方法。
任務1 - 建立API專案
在此任務中,您將使用新的ASP.NET Web專案模板來建立Web API Web應用程式。
執行Visual Studio 2012 Express for Web,執行此操作轉到“ 開始”,然後鍵入VS Express for Web,然後按Enter鍵。
從檔案選單中,選擇新建專案。選擇Visual C#| Web專案型別從專案型別樹檢視,然後選擇ASP.NET MVC 4 Web應用程式專案型別。將專案的名稱設定為ContactManager,並將解決方案名稱設定為開始,然後單擊確定。


建立一個新的ASP.NET MVC 4.0 Web應用程式專案
在ASP.NET MVC 4專案型別對話方塊中,選擇Web API專案型別。單擊確定。


指定Web API專案型別
任務2 - 建立Contact Manager API控制器
在此任務中,您將建立API方法所在的控制器類。
刪除檔名為ValuesController.cs內控制器從專案資料夾。
右鍵單擊專案中的Controllers資料夾,然後選擇Add | 控制器從上下文選單。


在專案中新增一個新的控制器
在顯示的新增控制器對話方塊中,從模板選單中選擇空API控制器。命名控制器類ContactController。然後,單擊新增。


使用新增控制器對話方塊建立一個新的Web API控制器
將以下程式碼新增到ContactController中。
(程式碼片段 - Web API實驗室 - Ex01 - 獲取API方法)
C#


複製
public string[] Get()
{
return new string[]
{
"Hello",
"World"
};
}
按F5除錯應用程式。出現Web API專案的預設主頁。


ASP.NET Web API應用程式的預設主頁
在Internet Explorer視窗中,按F12鍵開啟“ 開發工具”視窗。單擊網路選項卡,然後單擊開始捕獲按鈕開始捕獲到視窗中的網路流量。


開啟網路選項卡並啟動網路捕獲
使用/ api / contact在瀏覽器的位址列中附加URL,然後按Enter鍵。傳輸詳細資訊將顯示在網路捕獲視窗中。請注意,響應的MIME型別是application / json。這演示了預設輸出格式如何是JSON。


在網路檢視中檢視Web API請求的輸出
注意
此時Internet Explorer 10的預設行為將是詢問使用者是否希望儲存或開啟Web API呼叫產生的流。輸出將是包含Web API URL呼叫的JSON結果的文字檔案。不要取消對話方塊,以便能夠通過開發人員工具視窗來觀看響應的內容。
點選轉到詳細檢視按鈕檢視有關此API呼叫的響應的更多詳細資訊。


切換到詳細檢視
單擊“ 響應體”選項卡以檢視實際的JSON響應文字。


檢視網路監視器中的JSON輸出文字
任務3 - 建立聯絡人模型並增加聯絡人控制器
在此任務中,您將建立API方法所在的控制器類。
右鍵單擊Models資料夾,然後選擇Add | 類...從上下文選單。


向Web應用程式新增新模型
在“ 新增新專案”對話方塊中,命名新檔案Contact.cs,然後單擊“ 新增”。


建立新的聯絡人類檔案
將以下突出顯示的程式碼新增到Contact類中。
(程式碼片段 - Web API實驗室 - Ex01 - 聯絡課)


複製
[!code-csharp[Main](build-restful-apis-with-aspnet-web-api/samples/sample2.cs)]
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. 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.


Using Intellisense assistance for namespace declarations
Modify the code for the Get method so that it returns an array of Contact model instances.
(Code Snippet - Web API Lab - Ex01 - Returning a list of contacts)
C#


Copy
public Contact[] Get()
{
    return new Contact[]
    {
        new Contact
        {
            Id = 1,
            Name = "Glenn Block"
        },
        new Contact
        {
            Id = 2,
            Name = "Dan Roth"
        }
    };
}
Press F5 to debug the web application in the browser. To view the changes made to the response output of the API, perform the following steps.
Once the browser opens, press F12 if the developer tools are not open yet.
Click the Network tab.
Press the Start Capturing button.
Add the URL suffix /api/contact to the URL in the address bar and press the Enter key.
Press the Go to detailed view button.
選擇響應體選項卡。您應該看到一個JSON字串,表示Contact例項陣列的序列化形式。


JSON序列化輸出複雜的Web API方法呼叫
任務4 - 將功能提取到服務層
此任務將演示如何將功能提取到服務層,以便開發人員輕鬆將其服務功能與控制器層分開,從而實現實際執行的服務的可重用性。
在解決方案root中建立一個新資料夾,並將其命名為Services。為此,右鍵單擊ContactManager專案,選擇新增 | 新建資料夾,將其命名為服務。


建立服務資料夾
右鍵單擊“ 服務”資料夾,然後選擇“ 新增” 類...從上下文選單。


向Services資料夾新增一個新類
當出現新增新專案對話方塊時,命名新類ContactRepository,然後單擊新增。


建立一個類檔案以包含Contact Repository服務層的程式碼
將一個using指令新增到ContactRepository.cs檔案以包含模型名稱空間。


複製
[!code-csharp[Main](build-restful-apis-with-aspnet-web-api/samples/sample4.cs)]
將以下突出顯示的程式碼新增到ContactRepository.cs檔案中以實現GetAllContacts方法。
(程式碼段 - Web API實驗室 - Ex01 - Contact Repository)
C#


複製
public class ContactRepository
{
    public Contact[] GetAllContacts()
    {
        return new Contact[]
        {
new Contact
{
Id = 1,
Name = "Glenn Block"
},
new Contact
{
Id = 2,
Name = "Dan Roth"
}
        };
    }
}
Open the ContactController.cs file if it is not already open.
Add the following using statement to the namespace declaration section of the file.


Copy
[!code-csharp[Main](build-restful-apis-with-aspnet-web-api/samples/sample6.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.
(Code Snippet - Web API Lab - Ex01 - Contact Controller)
C#


Copy
public class ContactController : ApiController
{
    private ContactRepository contactRepository;


    public ContactController()
    {
        this.contactRepository = new ContactRepository();
    } 
    ...
}
Change the Get method so that it makes use of the contact repository service.
(Code Snippet - Web API Lab - Ex01 - Returning a list of contacts via the repository)
C#


Copy
public Contact[] Get()
{
    return contactRepository.GetAllContacts();
}
Put a breakpoint on the ContactController's Get method definition.


Adding breakpoints to the contact controller
Press F5 to run the application.
When the browser opens, press F12 to open the developer tools.
Click the Network tab.
Click the Start Capturing button.
Append the URL in the address bar with the suffix /api/contact and press Enter to load the API controller.
Visual Studio 2012 should break once Get method begins execution.


Breaking within the Get method
Press F5 to continue.
如果尚未對焦,請返回到Internet Explorer。注意網路捕獲視窗。


Internet Explorer中的網路檢視顯示Web API呼叫的結果
單擊轉到詳細檢視按鈕。
單擊響應體選項卡。請注意API呼叫的JSON輸出,以及它如何表示由服務層檢索的兩個聯絡人。


在開發人員工具視窗中檢視Web API中的JSON輸出
練習2:建立一個讀/寫Web API


在本練習中,您將為聯絡人管理員實施POST和PUT方法,使其具有資料編輯功能。
任務1 - 開啟Web API專案
在此任務中,您將準備增強在練習1中建立的Web API專案,以便它可以接受使用者輸入。
執行Visual Studio 2012 Express for Web,執行此操作轉到“ 開始”,然後鍵入VS Express for Web,然後按Enter鍵。
開啟位於Source / Ex02-ReadWriteWebAPI / Begin /資料夾的Begin解決方案。否則,您可以繼續使用通過完成上一個練習獲得的最終解決方案。
如果您開啟提供的Begin解決方案,則需要在繼續之前下載一些缺少的NuGet軟體包。為此,單擊專案選單並選擇管理NuGet軟體包。
在“ 管理NuGet軟體包”對話方塊中,單擊“恢復”,以便下載丟失的軟體包。
最後,單擊Build | 構建解決方案 生成解決方案。
注意
使用NuGet的優點之一是您不必在專案中運送所有庫,從而減少了專案的大小。使用NuGet電動工具,通過在Packages.config檔案中指定軟體包版本,您可以在首次執行專案時下載所有必需的庫。這就是為什麼在開啟本實驗室的現有解決方案之後,您必須執行這些步驟。
開啟Services / ContactRepository.cs檔案。
任務2 - 將資料永續性功能新增到聯絡人庫實現
在此任務中,您將擴充套件在練習1中建立的Web API專案的ContactRepository類,以便它可以持久化並接受使用者輸入和新的Contact例項。
將以下常量新增到ContactRepository類以在本練習中稍後表示Web伺服器快取專案鍵名稱的名稱。
C#


複製
private const string CacheKey = "ContactStore";
向包含以下程式碼的ContactRepository新增建構函式。
(程式碼片段 - Web API實驗室 - Ex02 - 聯絡人儲存庫建構函式)
C#


複製
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;
        }
    }
}
修改GetAllContacts方法的程式碼,如下所示。
(程式碼片段 - Web API實驗室 - Ex02 - 獲取所有聯絡人)
C#


複製
public Contact[] GetAllContacts()
{
    var ctx = HttpContext.Current;


    if (ctx != null)
    {
        return (Contact[])ctx.Cache[CacheKey];
    }


    return new Contact[]
        {
            new Contact
            {
                Id = 0,
                Name = "Placeholder"
            }
        };
}
注意
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. One could use Entity Framework, XML storage, or any other variety in place of the web server cache.
Implement a new method named SaveContact to the ContactRepository class to do the work of saving a contact. The SaveContact method should take a single Contact parameter and return a Boolean value indicating success or failure.
(Code Snippet - Web API Lab - Ex02 - Implementing the SaveContact Method)
C#


Copy
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;
}
Exercise 3: Consume the Web API from an HTML Client


In this exercise, you will create an HTML client to call the Web API. This client will facilitate data exchange with the Web API using JavaScript and will display the results in a web browser using HTML markup.
Task 1 - Modifying the Index View to Provide a GUI for Displaying Contacts
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.
Open Visual Studio 2012 Express for Web if it is not already open.
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.
如果您開啟提供的Begin解決方案,則需要在繼續之前下載一些缺少的NuGet軟體包。為此,單擊專案選單並選擇管理NuGet軟體包。
在“ 管理NuGet軟體包”對話方塊中,單擊“恢復”,以便下載丟失的軟體包。
最後,單擊Build | 構建解決方案 生成解決方案。
注意
使用NuGet的優點之一是您不必在專案中運送所有庫,從而減少了專案的大小。使用NuGet電動工具,通過在Packages.config檔案中指定軟體包版本,您可以在首次執行專案時下載所有必需的庫。這就是為什麼在開啟本實驗室的現有解決方案之後,您必須執行這些步驟。
開啟位於Views / Home資料夾的Index.cshtml檔案。
用id body替換div元素中的HTML程式碼,使其看起來像以下程式碼。


複製
[!code-html[Main](build-restful-apis-with-aspnet-web-api/samples/sample13.html)]
在檔案底部新增以下Javascript程式碼,以執行對Web API的HTTP請求。


複製
[!code-cshtml[Main](build-restful-apis-with-aspnet-web-api/samples/sample14.cshtml)]
開啟ContactController.cs檔案(如果尚未開啟)。
在ContactController類的Get方法上放置一個斷點。


在API控制器的Get方法上放置一個斷點
按F5執行專案。瀏覽器將載入HTML文件。
注意
確保您正在瀏覽應用程式的根URL。
一旦頁面載入並且JavaScript執行,斷點將被擊中,程式碼執行將在控制器中暫停。


使用Visual Studio 2012 Express for Web除錯Web API呼叫
刪除斷點,然後按F5或除錯工具欄的“ 繼續”按鈕繼續在瀏覽器中載入檢視。Web API呼叫完成後,您將看到從Web API呼叫返回的聯絡人顯示為瀏覽器中的列表項。


作為列表項顯示在瀏覽器中的API呼叫結果
停止除錯
任務2 - 修改索引檢視以提供用於建立聯絡人的GUI
在此任務中,您將繼續修改MVC應用程式的索引檢視。一個表單將新增到HTML頁面中,該頁面將捕獲使用者輸入並將其傳送到Web API以建立新的聯絡人,並且將建立一個新的Web API控制器方法以從GUI收集日期。
開啟ContactController.cs檔案。
向名為Post的控制器類新增一個新方法,如下面的程式碼所示。
(程式碼段 - Web API實驗室 - Ex03 - Post方法)


複製
[!code-csharp[Main](build-restful-apis-with-aspnet-web-api/samples/sample15.cs)]
如果Visual Studio中尚未開啟,請開啟Index.cshtml檔案。
將下面的HTML程式碼新增到上一個任務中新增的無序列表之後的檔案中。


複製
[!code-html[Main](build-restful-apis-with-aspnet-web-api/samples/sample16.html)]
在文件底部的指令碼元素中,新增以下突出顯示的程式碼來處理按鈕單擊事件,這將使用HTTP POST呼叫將資料釋出到Web API。
HTML


複製
<script type="text/javascript">
... 
$('#saveContact').click(function()
         {
              $.post("api/contact",
                    $("#saveContactForm").serialize(),
                    function(value)
                    {
                         $('#contacts').append('<li>' + value.Name + '</li>');
                    },
                    "json"
              );
         });
</script>
在ContactController.cs中,在Post方法上放置一個斷點。
按F5在瀏覽器中執行應用程式。
頁面在瀏覽器中載入後,輸入新的聯絡人姓名和ID,然後單擊儲存按鈕。


在瀏覽器中載入的客戶端HTML文件
當Post方法中的偵錯程式視窗中斷時,請檢視contact引數的屬性。這些值應與您在表單中輸入的資料相匹配。


Contact物件從客戶端傳送到Web API
在偵錯程式中遍歷方法,直到建立響應變數。在偵錯程式的“ 本地”視窗中進行檢查後,您將看到所有屬性都已設定。


在偵錯程式中建立後的響應
如果按F5或在偵錯程式中單擊繼續,則請求將完成。一旦您切換回瀏覽器,新的聯絡人已被新增到由ContactRepository實現儲存的聯絡人列表中。


瀏覽器反映了新的聯絡人例項的成功建立
注意
此外,您可以將此應用程式部署到Azure,方法如下:附錄C:使用Web Deploy釋出ASP.NET MVC 4應用程式。
概要
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 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. 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.
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). 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.
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.


Using Visual Studio code snippets to insert code into your project
To add a code snippet using the keyboard (C# only)


Place the cursor where you would like to insert the code.
Start typing the snippet name (without spaces or hyphens).
Watch as IntelliSense displays matching snippets' names.
Select the correct snippet (or keep typing until the entire snippet's name is selected).
Press the Tab key twice to insert the snippet at the cursor location.


Start typing the snippet name


Press Tab to select the highlighted snippet


Press Tab again and the snippet will expand
To add a code snippet using the mouse (C#, Visual Basic and XML)


Right-click where you want to insert the code snippet.
Select Insert Snippet followed by My Code Snippets.
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


Pick the relevant snippet from the list, by clicking on it
Appendix B: Installing Visual Studio Express 2012 for Web
You can install Microsoft Visual Studio Express 2012 for Web or another "Express" version using the Microsoft Web Platform Installer. The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.
Go to [https://go.microsoft.com/?linkid=9810169](https://go.microsoft.com/?linkid=9810169). 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".
點選立即安裝。如果您沒有Web平臺安裝程式,您將被重定向下載並首先安裝。
一旦Web平臺安裝程式開啟後,點選安裝,開始安裝。


安裝Visual Studio Express
閱讀所有產品的許可證和條款,然後單擊我接受以繼續。


接受許可條款
等待下載和安裝過程完成。


安裝進度
安裝完成後,單擊完成。


安裝完成
單擊退出以關閉Web平臺安裝程式。
要開啟Visual Studio Express for Web,請轉到“ 開始”螢幕並開始編寫“ VS Express ”,然後單擊VS Express for Web tile。


VS Express for Web瓦片
附錄C:使用Web Deploy釋出ASP.NET MVC 4應用程式
本附錄將向您展示如何從Azure Portal建立新的網站,併發布您通過實驗室獲得的應用程式,利用Azure提供的Web部署釋出功能。
任務1 - 從Azure Portal建立新的網站
轉到Azure管理門戶並使用與您的訂閱關聯的Microsoft憑據登入。
注意
使用Azure,您可以免費託管10個ASP.NET網站,然後隨著流量的增長而擴充套件。你可以註冊在這裡。


登入到Portal
在命令欄上單擊新建。


建立一個新的網站
單擊計算 | 網站。然後選擇快速建立選項。為新網站提供可用的URL,然後單擊建立網站。
注意
Azure是執行在雲中的Web應用程式的主機,可以進行控制和管理。“快速建立”選項允許您從門戶外部署完整的Web應用程式到Azure。它不包括設定資料庫的步驟。


使用快速建立建立一個新的網站
等到建立新的網站。
建立網站後,請單擊URL列下的連結。檢查新的網站是否正常工作。


瀏覽新的網站


網站執行
返回入口網站,單擊“名稱” 列下的網站名稱以顯示管理頁面。


開啟網站管理頁面
在“ 儀表板”頁面中的快速瀏覽部分下,單擊“ 下載釋出配置檔案”連結。
注意
將釋出配置檔案包含所有釋出的Web應用程式到Azure的每個被允許的出版物方法所需要的資訊。釋出配置檔案包含連線到和啟用釋出方法的每個端點進行身份驗證所需的URL,使用者憑據和資料庫字串。Microsoft WebMatrix 2,用於Web和Microsoft Visual Studio 2012的Microsoft Visual Studio Express支援閱讀釋出配置檔案,以自動配置這些將Web應用程式釋出到Azure的程式。


下載網站釋出個人資料
將釋出配置檔案下載到已知位置。進一步在本練習中,您將看到如何使用此檔案將Web應用程式從Visual Studio釋出到Azure。


儲存釋出配置檔案
任務2 - 配置資料庫伺服器
如果您的應用程式使用SQL Server資料庫,則需要建立一個SQL資料庫伺服器。如果要部署一個不使用SQL Server的簡單應用程式,則可以跳過此任務。
您將需要一個用於儲存應用程式資料庫的SQL資料庫伺服器。您可以從您在Azure管理入口網站的訂閱檢視SQL資料庫伺服器SQL資料庫 | 伺服器 | 伺服器的儀表盤。如果您沒有建立伺服器,可以使用命令欄上的“ 新增”按鈕建立一個伺服器。記下伺服器名稱和URL,管理員登入名和密碼,您將在下一個任務中使用它們。不要建立資料庫,因為它將在稍後的階段建立。


SQL資料庫伺服器儀表板
在下一個任務中,您將從Visual Studio測試資料庫連線,因此您需要將本地IP地址包含在伺服器的允許的IP地址列表中。為此,單擊配置,從當前客戶端IP地址中選擇IP地址,並將其貼上到“ 開始IP地址和結束IP地址”文字框中,然後單擊該按鈕。


新增客戶端IP地址
將客戶端IP地址新增到允許的IP地址列表後,單擊儲存以確認更改。


確認更改
任務3 - 使用Web Deploy釋出ASP.NET MVC 4應用程式
回到ASP.NET MVC 4解決方案。在解決方案資源管理器中,右鍵單擊網站專案,然後選擇釋出。


釋出網站
匯入您儲存在第一個任務中的釋出配置檔案。


匯入釋出配置檔案
單擊驗證連線。驗證完成後,單擊下一步。
注意
一旦您在驗證連線按鈕旁邊看到綠色複選標記,驗證就會完成。


驗證連線
在“ 設定”頁面的“ 資料庫”部分下,單擊資料庫連線的文字框旁邊的按鈕(即DefaultConnection)。


Web部署配置
配置資料庫連線如下:
在伺服器名稱中,使用tcp: prefix 鍵入SQL資料庫伺服器URL 。
在使用者名稱中輸入您的伺服器管理員登入名。
在密碼中鍵入伺服器管理員登入密碼。
鍵入新的資料庫名稱,例如:MVC4SampleDB。


配置目標連線字串
然後單擊確定。當提示建立資料庫時,單擊是。


建立資料庫
您將用於連線到Windows Azure中的SQL資料庫的連線字串顯示在“預設連線”文字框中。然後單擊下一步。


指向SQL資料庫的連線字串
在“ 預覽”頁面中,單擊“ 釋出”。


釋出Web應用程式
一旦釋出過程完成,您的預設瀏覽器將開啟已釋出的網站。


應用程式釋出到Azure

相關文章