最近做了一個項目技術預研:在ASP.NET MVC框架中使用Web API和EntityFramework,構建一個基礎的架構,並在此基礎上實現基本的CRUD應用。
以下是詳細的步驟。
第一步
在數據庫中創建一張數據表,表名為Customer,見下圖:
第二步
-
打開 Visual Studio,新建項目。
-
選擇'ASP.NET Web Application',命名為'WebApi'。
-
我們要創建一個'Web API',在模板中選擇'Web API',點擊'確定'。
第三步
接下來我要添加一個類。
-
右鍵點擊這個 web api項目,添加一個'ADO.NET Entity Data Model'。
-
添加'EF Designer from database',點擊'下一步'。
-
在配置窗口中添加新連接,輸入服務器名稱,選擇數據庫,點擊'確定'。
-
點擊'下一步',選擇要關聯的數據表。
-
點擊'完成'。
第四步
現在的工作就是要為Wep Api添加控制器了。
-
右鍵選擇'controllers'文件夾。
-
選擇'MVC5 Controller with views, using Entity Framework'。
-
點擊'添加'。
-
選擇數據模型類Customer,選擇Data context類文件,本例中為SystemTestEntity。
-
設置控制器名稱為CustomersController,點擊'添加'。
上述操作完成后,CustomerController.cs會自動生成。
CustomerController.cs
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using CRUDWebApiExam.Models;
namespace CRUDWebApiExam.Controllers
{
public class CustomersController : ApiController
{
private SystemTestEntities db = new SystemTestEntities();
// GET: api/Customers
public IQueryable<Customer> GetCustomer()
{
return db.Customer;
}
// GET: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult GetCustomer(int id)
{
Customer customer = db.Customer.Find(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
// PUT: api/Customers/5
[ResponseType(typeof(void))]
public IHttpActionResult PutCustomer(int id, Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.CustomerId)
{
return BadRequest();
}
db.Entry(customer).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Customers
[ResponseType(typeof(Customer))]
public IHttpActionResult PostCustomer(Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Customer.Add(customer);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = customer.CustomerId }, customer);
}
// DELETE: api/Customers/5
[ResponseType(typeof(Customer))]
public IHttpActionResult DeleteCustomer(int id)
{
Customer customer = db.Customer.Find(id);
if (customer == null)
{
return NotFound();
}
db.Customer.Remove(customer);
db.SaveChanges();
return Ok(customer);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool CustomerExists(int id)
{
return db.Customer.Count(e => e.CustomerId == id) > 0;
}
}
}
運行這個 Web Api項目,你會看到下面的結果
第五步
到此為止,web api已經構建成功了。接下來我們需要為這個web api服務添加消費對象了,這個消費對象就是本文要涉及的MVC項目。
- 首先要添加一個model類,我們可以直接采用上文中的Customer類。右鍵點擊models文件夾,添加類並命名。本例中,我直接命名為Customer.cs。
Customer.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace MVCPersatantion.Models
{
public class Customer
{
[Display(Name = "CustomerId")]
public int CustomerId { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string Address { get; set; }
[Display(Name = "MobileNo")]
public string MobileNo { get; set; }
[Display(Name = "Birthdate")]
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
[Display(Name = "EmailId")]
public string EmailId { get; set; }
}
}
- customer類添加完成后,接下來需要添加一個ViewModel文件夾,並在里面新建一個CustomerViewModel.cs文件。
CustomerViewModel.cs
using MVCPersatantion.Models;
namespace MVCPersatantion.ViewModel
{
public class CustomerViewModel
{
public Customer customer { get; set; }
}
}
第六步
我已經添加了一個消費web api服務的類,現在我還需要添加一個Client類。
- 右鍵點擊models文件夾,添加類文件CustomerClient.cs。
CustomerClient.cs
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MVCPersatantion.Models
{
public class CustomerClient
{
private string Base_URL = "http://localhost:30110/api/";
public IEnumerable<Customer> findAll()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Base_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("customers").Result;
if (response.IsSuccessStatusCode)
return response.Content.ReadAsAsync<IEnumerable<Customer>>().Result;
return null;
}
catch
{
return null;
}
}
public Customer find(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Base_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("customers/" + id).Result;
if (response.IsSuccessStatusCode)
return response.Content.ReadAsAsync<Customer>().Result;
return null;
}
catch
{
return null;
}
}
public bool Create(Customer customer)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Base_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("customers", customer).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Edit(Customer customer)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Base_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsJsonAsync("customers/" + customer.CustomerId, customer).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public bool Delete(int id)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Base_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.DeleteAsync("customers/" + id).Result;
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
}
}
細心的朋友們可能已經發現,我的代碼中有一些重復代碼。實際應用中我們可以抽取成公用代碼,這樣任何地方都能夠使用了。這里為了清楚的闡述過程,所以寫了一些重復的代碼。
我們看第一行private string Base_URL = "http://localhost:50985/api/"
,這個Base_URL是web api的服務地址。
接下來就可以編寫Insert、Update、Delete、Select的業務邏輯了。
第七步
右鍵點擊Controllers文件夾,添加一個名為Customer控制器,控制器中添加服務客戶端調用的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCPersatantion.Models;
using MVCPersatantion.ViewModel;
namespace MVCPersatantion.Controllers
{
public class CustomerController : Controller
{
// GET: Customer
public ActionResult Index()
{
CustomerClient CC = new CustomerClient();
ViewBag.listCustomers = CC.findAll();
return View();
}
[HttpGet]
public ActionResult Create()
{
return View("Create");
}
[HttpPost]
public ActionResult Create(CustomerViewModel cvm)
{
CustomerClient CC = new CustomerClient();
CC.Create(cvm.customer);
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
CustomerClient CC = new CustomerClient();
CC.Delete(id);
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Edit(int id)
{
CustomerClient CC = new CustomerClient();
CustomerViewModel CVM = new CustomerViewModel();
CVM.customer = CC.find(id);
return View("Edit",CVM);
}
[HttpPost]
public ActionResult Edit(CustomerViewModel CVM)
{
CustomerClient CC = new CustomerClient();
CC.Edit(CVM.customer);
return RedirectToAction("Index");
}
}
}
第八步
-
創建視圖頁面Index.cshtml。
-
在Index頁面中添加代碼。
Index.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div align="center">
@Html.ActionLink("Create", "Create", "Customer", new { area = "" }, null)
<br /><br />
<table cellpadding="2"
class="table"
cellspacing="2"
border="1">
<tr class="btn-primary">
<th>
CustomerId
</th>
<th> Name</th>
<th> Address</th>
<th> MobileNo</th>
<th> Birthdate</th>
<th> EmailId</th>
<th> Action</th>
</tr>
@foreach (var Cust in ViewBag.listCustomers)
{
<tr class="btn-success">
<td>
@Cust.CustomerId
</td>
<td>
@Cust.Name
</td>
<td>
@Cust.Address
</td>
<td>
@Cust.MobileNo
</td>
<td>
@Cust.Birthdate.ToString("dd/MM/yyyy")
</td>
<td>
@Cust.EmailId
</td>
<td>
<a onclick="return confirm('確定要刪除這條數據?')"
href="@Url.Action("Delete","Customer",new {id= Cust.CustomerId})">Delete</a> ||
<a href="@Url.Action("Edit","Customer",new {id= Cust.CustomerId})">Edit</a>
@*@Html.ActionLink("Edit", "Edit", "Customer", new { id = Cust.CustomerId })*@
</td>
</tr>
}
</table>
</div>
-
添加新增數據模塊Create。
-
在Customer控制器中添加create方法,在view中增加Create.cshtml。
Create.cshtml
@model WebApiMVC.ViewModel.CustomerViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<div align = "center" >
@using (Html.BeginForm("create", "Customer", FormMethod.Post))
{
<table class="table">
<tr>
<td>
@Html.LabelFor(model => model.customer.Name)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Name)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.Address)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Address)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.MobileNo)
</td>
<td>
@Html.TextBoxFor(model => model.customer.MobileNo)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.Birthdate)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Birthdate)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.EmailId)
</td>
<td>
@Html.TextBoxFor(model => model.customer.EmailId)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="保存" />
</td>
</tr>
</table>
}
</div>
-
添加修改數據模塊Edit。
-
在Customer控制器中添加edit方法,在view中增加Edit.cshtml。
Edit.cshtml
@{
ViewBag.Title = "Edit";
}
@model WebApiMVC.ViewModel.CustomerViewModel
<h2> Edit </h2>
<div align="center" width="500px">
@using (Html.BeginForm("Edit", "Customer", FormMethod.Post))
{
<table class="table"
width="400px"
cellpadding="20">
<tr class="btn-default">
<td>
@Html.LabelFor(model => model.customer.Name)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Name)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.Address)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Address)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.MobileNo)
</td>
<td>
@Html.TextBoxFor(model => model.customer.MobileNo)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.Birthdate)
</td>
<td>
@Html.TextBoxFor(model => model.customer.Birthdate)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.customer.EmailId)
</td>
<td>
@Html.TextBoxFor(model => model.customer.EmailId)
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="保存" /> <a class="btn-primary" href="@Url.Action("Index ","Customer ")"> 返回 </a>
@Html.HiddenFor(model => model.customer.CustomerId)
</td>
</tr>
</table>
}
</div>
最終項目代碼已經完成了。這時候我們運行項目試試看了。但還有一點要注意的是,我們必須同時運行web api和mvc項目。怎么辦呢?其實只要在項目屬性里設置就可以了。
- 右鍵解決方案,選擇屬性(Properties)。
-
接來下在啟動項目選項中,選擇
多項目啟動
,在Action
中設置兩個項目同時啟動。 -
運行項目,看看CRUD操作的執行結果。
Select
Insert
Update
Delete
這是整個技術預研的過程,本文末尾位置提供代碼下載。
博客地址: http://www.cnblogs.com/yayazi/
本文地址: http://www.cnblogs.com/yayazi/p/8444054.html
聲明:本博客原創文字允許轉載,轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
源碼下載: https://github.com/daivven/WebApiMVC
PS:本人近期打算換工作,目標地點武漢,目標職位.Net軟件工程師,期望月薪資12k以上,春節后可參加面試。有沒有園友有合適崗位推薦,私信我可發簡歷,求內推哇~