在上一篇裏,我已經創建了一個簡單的Web-Demo應用程序。這一篇將記錄將此Demo程序改形成一個Web Api應用程序。html
1. 在project.json文件添加Microsoft.AspNetCore.Mvc包json
1 { 2 "version": "1.0.0-*", 3 "buildOptions": { 4 "debugType": "portable", 5 "emitEntryPoint": true 6 }, 7 "dependencies": { 8 "Microsoft.NETCore.App": { 9 "type": "platform", 10 "version": "1.0.0" 11 }, 12 "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", 13 "Microsoft.AspNetCore.Mvc": "1.0.0" 14 }, 15 "frameworks": { 16 "netcoreapp1.0": { 17 "imports": "dnxcore50" 18 } 19 } 20 }
2. 在cmd窗口使用 dotnet restore 將新添加的包還原至本地api
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.Extensions.DependencyInjection; 3 4 namespace WebApiFrame 5 { 6 public class Startup 7 { 8 public void ConfigureServices(IServiceCollection services) 9 { 10 11 // 注入MVC框架 12 services.AddMvc(); 13 } 14 15 public void Configure(IApplicationBuilder app) 16 { 17 // 添加MVC中間件 18 app.UseMvc(); 19 } 20 } 21 }
1. 控制器UsersControllerapp
1 using System; 2 using Microsoft.AspNetCore.Mvc; 3 using WebApiFrame.Models; 4 5 namespace WebApiFrame.Controller 6 { 7 8 [Route("api/[controller]")] 9 public class UsersController : Microsoft.AspNetCore.Mvc.Controller 10 { 11 12 [HttpGet("{id}")] 13 public IActionResult Get(int id) 14 { 15 var user = new User() { Id = id, Name = "Name:" + id, Sex = "Male" }; 16 return new ObjectResult(user); 17 } 18 19 [HttpPost] 20 public IActionResult Post([FromBody] User user){ 21 if(user == null){ 22 return BadRequest(); 23 } 24 25 // TODO:新增操做 26 user.Id = new Random().Next(1, 10); 27 return CreatedAtAction("Get", new { id = user.Id }, user); 28 } 29 30 [HttpPut("{id}")] 31 public IActionResult Put(int id, [FromBody] User user){ 32 if(user == null){ 33 return BadRequest(); 34 } 35 36 // TODO: 更新操做 37 return new NoContentResult(); 38 } 39 40 [HttpDelete("{id}")] 41 public void Delete(int id){ 42 // TODO: 刪除操做 43 44 } 45 } 46 }
不一樣於以前的ASP.NET MVC版本,ASP.NET Core MVC裏實現Web Api的控制器都繼承自惟一的一個基類Controller。框架
2. 模型User.csdom
1 namespace WebApiFrame.Models 2 { 3 public class User 4 { 5 public int Id { get; set; } 6 public string Name { get; set; } 7 public string Sex { get; set; } 8 } 9 }
最終文件夾結構以下圖工具
1. GET Requestui
GET Responseurl
2. POST Requestspa
POST Response
POST響應碼爲201,表示資源建立成功。
在響應頭裏有一個Location屬性,這是一個導航屬性,屬性值是一個url地址,直接指向了剛剛Post成功的資源地址。
3. PUT Request
PUT Response
PUT爲更新操做。按照規範,當服務更新操做執行成功後,直接經過響應碼204告訴客戶端調用成功,默認沒有響應body。
4. DELETE Request
DELETE Response
DELETE爲刪除操做。按照規範,須要經過響應碼判斷是否成功(200)仍是失敗(500),默認沒有響應body。