標籤:
最近看到windows azure 在做活動,只需花一塊錢就可以體驗一個月的windows azure. 於是,我就註冊了一個帳號也嘗試一把雲時代,傳送門。 註冊很簡單的,成功後可以看到這個介面。
然後,我就研究了一下怎麼把網站發布到雲上,在此分享一下。網站是簡單的基於asp.net mvc + code first 比較簡單。
首先建立一個asp.net mvc 的網站。在此我命名為 WindowsAzureMVC,為了支援code first 需要添加entity framework 的dll。右鍵管理NUGET程式包 添加EntityFramework.
在web.config 檔案中添加節點:
1 <connectionStrings>2 <add name="TestConnect" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Test;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />3 </connectionStrings>
再建立一個AzureDataContext類
1 public class AzureDataContext : DbContext 2 { 3 public AzureDataContext() 4 : base("name=TestConnect") 5 { 6 7 } 8 9 public DbSet<User> User { get; set; }10 }11 12 public class User13 {14 public Guid Id { get; set; }15 16 public string Name { get; set; }17 18 public int Age { get; set; }19 }
這個就是簡單的資料了,表示一個資料庫有一個表叫做User。
然後運行nuget命令 先開啟Nuget 控制台 視圖-》其他視窗-》封裝管理員控制台。
輸入Enable-Migrations 會自動產生一個Configuration類
1 internal sealed class Configuration : DbMigrationsConfiguration<WindowsAzureMVC.Data.AzureDataContext> 2 { 3 public Configuration() 4 { 5 AutomaticMigrationDataLossAllowed = true; 6 AutomaticMigrationsEnabled = true; 7 } 8 9 protected override void Seed(WindowsAzureMVC.Data.AzureDataContext context)10 {11 context.User.AddOrUpdate(p => p.Id, new User() { Id = Guid.NewGuid(), Age = 1, Name = "test" });12 13 }14 }
我在seed 方法中加了一個初始化資料。
然後輸入 update-database 命令,成功之後 會看到產生的資料庫。
然後我在 MVC的controller 和view 裡寫了一些簡單的代碼。
1 public ActionResult Index() 2 { 3 User user = new Data.User() { Id = Guid.NewGuid(), Name = "test", Age = new Random().Next(1, 100) }; 4 5 azureDataContext.User.Add(user); 6 azureDataContext.SaveChanges(); 7 List<User> userList = azureDataContext.User.ToList(); 8 9 return View(userList);10 }
1 @model List<WindowsAzureMVC.Data.User> 2 @{ 3 ViewBag.Title = "Home Page"; 4 } 5 <div class="row"> 6 <table class="table table-bordered"> 7 <caption>使用者列表</caption> 8 <thead> 9 <tr>10 <th>姓名</th>11 <th>年齡</th>12 </tr>13 </thead>14 <tbody>15 @foreach (var item in Model)16 {17 <tr>18 <td>19 @item.Name20 </td>21 <td>22 @item.Age23 </td>24 </tr>25 }26 </tbody>27 </table>28 </div>
OK, 網站這邊基本完成,比較簡單的示範。
然後發布,首先我需要建立一個資料庫,
然後建立一個網站,
之後我需要下載發行設定檔,
下載的檔案名稱叫justtest.chinacloudsites.cn.PublishSettings 之後就發行就緒了,
右鍵 -》 發布
點擊發布成功。地址是 http://justtest.chinacloudsites.cn/
基本搞定收工。這就是我的azure 初體驗。
Windows Azure 初體驗