สร้างโปรเจ็กส์ชื่อ grocery แบบ mvc
[code]
> mkdir grocery
> cd grocery
> dotnet new mvc
[/code]
ทดสอบรัน
[code]
> dotnet run
[/code]
เข้าได้ที่ https://localhost:5001/
Creating the Grocery List API
สร้างโฟลเดอร์ Data
สร้างไฟล์
Models/GroceryItem.cs
Data/GroceryListContext.cs
Controllers/GroceryListController.cs
Models/GroceryItem.cs
1 2 3 4 5 6 7 8 |
namespace grocery.Models { public class GroceryItem { public long Id { get; set; } public string Description { get; set; } } } |
Data/GroceryListContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using grocery.Models; using Microsoft.EntityFrameworkCore; namespace grocery.Data { public class GroceryListContext : DbContext { public GroceryListContext(DbContextOptions<GroceryListContext> options) : base(options) { } public DbSet<GroceryItem> GroceryList { get; set; } } } |
Controllers/GroceryListController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
using grocery.Data; using grocery.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; namespace grocery.Controllers { [Route("api/[controller]")] public class GroceryListController : Controller { private readonly GroceryListContext _context; public GroceryListController(GroceryListContext context) { _context = context; if (_context.GroceryList.Count() == 0) { _context.GroceryList.Add(new GroceryItem { Description = "Item1" }); _context.GroceryList.Add(new GroceryItem { Description = "Item2" }); _context.GroceryList.Add(new GroceryItem { Description = "Item3" }); _context.GroceryList.Add(new GroceryItem { Description = "Item4" }); _context.GroceryList.Add(new GroceryItem { Description = "Item5" }); _context.SaveChanges(); } } [HttpGet] public IEnumerable<GroceryItem> GetAll() { return _context.GroceryList.ToList(); } [HttpGet("{id}", Name = "GetGroceryItem")] public IActionResult GetById(long id) { var item = _context.GroceryList.FirstOrDefault(t => t.Id == id); if (item == null) { return NotFound(); } return new ObjectResult(item); } [HttpPost] public IActionResult Create([FromBody] GroceryItem item) { if (item == null) { return BadRequest(); } _context.GroceryList.Add(item); _context.SaveChanges(); return CreatedAtRoute("GetGroceryItem", new { id = item.Id }, item); } [HttpDelete("{id}")] public IActionResult Delete(long id) { var item = _context.GroceryList.First(t => t.Id == id); if (item == null) { return NotFound(); } _context.GroceryList.Remove(item); _context.SaveChanges(); return new NoContentResult(); } } } |
บรรทัดที่ 19 : ถ้าไม่มีข้อมูลอยู่ ให้สร้างข้อมูล dummy ขึ้นมา 5 ตัว
Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
using grocery.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace grocery { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext<GroceryListContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } } |
appsettings.json
1 2 3 4 5 6 7 8 9 10 11 |
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=grocery;Trusted_Connection=True;MultipleActiveResultSets=true" } } |
Perform initial migration
[code]
> dotnet ef migrations add Initial
> dotnet ef database update
[/code]
ทดสอบการทำงาน
[code]
> dotnet run
[/code]
เข้าได้ที่ https://localhost:5001/api/grocerylist/1
จะได้ {"id":1,"description":"Item1"}
เข้าได้ที่ https://localhost:5001/api/grocerylist
จะได้ [{"id":1,"description":"Item1"},{"id":2,"description":"Item2"},{"id":3,"description":"Item3"},{"id":4,"description":"Item4"},{"id":5,"description":"Item5"}]
ลองใช้ Postman ทำการ POST เพื่อเป็นการเพิ่มข้อมูล
กำหนด url เป็น https://localhost:5001/api/grocerylist
พารามิเตอร์ส่งใน body เป็น
[code]
{
"description":"Item6"
}
[/code]
ลองใช้ Postman ทำการ DELETE เพื่อเป็นการลบข้อมูลที่มี id=3
กำหนด url เป็น https://localhost:5001/api/grocerylist/3
เข้าแบบ GET อีกที่ https://localhost:5001/api/grocerylist
ทีนี้จะได้
[code]
[
{
"id": 1,
"description": "Item1"
},
{
"id": 2,
"description": "Item2"
},
{
"id": 4,
"description": "Item4"
},
{
"id": 5,
"description": "Item5"
},
{
"id": 6,
"description": "Item6"
}
]
[/code]
Link