Tạo Web API

  • Nội dung

    • Tạo mới Project
  • Tạo Project mới

    • Khi tạo, chọn ASP.NET Core Web Application -> Api (nếu muốn làm web services) -> Run
  • Quản lý các Models

    • Tạo thư mục quản lý các models (New Models Folder)
    • Tạo lớp TodoItem trong thư mục Models
namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}
  • Tạo lớp Database Context

    • Lớp TodoContext là lớp trong gian trong việc lấy dữ liệu hoặc gán dữ liệu
using Microsoft.EntityFrameworkCore;

namespace GetStartDemo.Models
{
    public class TodoContext : DbContext
    {
        // :base (options) gọi Contructer của lớp DbContext
        public TodoContext(DbContextOptions options) : base (options) {

        }

        //Tạo biến để gán hoặc lấy dữ liệu TodoItem từ database
        public DbSet TodoItems { get; set; }
    }
}
  • Cài đặt kết nối dữ Database và DbContext

    • Đăng ký lớp trong file Startup của Project
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using TodoApi.Models;

namespace TodoApi
{
    public class Startup
    {       
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(opt => 
                opt.UseInMemoryDatabase("TodoList"));
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}
  • Tạo controller

    • Tạo TodoController trong folder Controller
    • 1
using Microsoft.AspNetCore.Mvc;
using GetStartDemo.Models;
using System.Linq;
using System.Collections.Generic;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace GetStartDemo.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        private readonly TodoContext _context;

        public TodoController(TodoContext context)
        {
            _context = context;
            
            if (_context.TodoItems.Count() == 0)
            {
                _context.TodoItems.Add(new TodoItem { Name = "Item1"});
                _context.SaveChanges();
            }
        }


        //Hàm lấy tất cả TodoItem
        [HttpGet]
        public List GetAll()
        {
            return _context.TodoItems.ToList();
        }

        //Lấy băng Id
        [HttpGet("{id}", Name = "GetToDo")]
        public IActionResult GetById(long id)
        {
            var item = _context.TodoItems.Find(id);
            if (item == null)
            {
                return NotFound();
            }

            return Ok();
        }


        //Hàm khởi tạo TodoItem
        [HttpPost]
        public IActionResult Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                //Lúc làm nên tạo 1 lớp quản lý các response trả về
                return BadRequest();
            }

            _context.TodoItems.Add(item);
            _context.SaveChanges();

            return CreatedAtRoute("GetToDo", new { id = item.Id}, item);
        }


        //Cập nhật TodoItem
        [HttpPut("{id}")]
        public IActionResult Update(long id, [FromBody]TodoItem item)
        {
            if (item == null && id != item.Id)
            {
                return BadRequest();
            }

            var todo = _context.TodoItems.Find(id);
            if (todo == null)
            {
                return NotFound();
            }

            todo.Name = item.Name;
            todo.IsComplete = item.IsComplete;

            _context.TodoItems.Update(todo);
            _context.SaveChanges();

            return NoContent();
        }

        //Xóa TodoItem
        [HttpDelete("{id}")]
        public IActionResult Delete(long id)
        {
            var todo = _context.TodoItems.Find(id);
            if (todo == null)
            {
                return NotFound();
            }

            _context.TodoItems.Remove(todo);
            _context.SaveChanges();
            return NotFound();
        }
    }
}
  •  Cài đặt swagger

    • Chọn Manager -> Gõ tìm Swashbuckle -> Install1.png
using GetStartDemo.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace GetStartDemo
{
    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.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList"));
            services.AddMvc();

            //Cấu hình swagger
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info{ Title = "Core API", Description = "Swagger Core API" });
            });
        }

        // 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();
            }

            app.UseMvc();

            //Cấu hình swagger
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API");
            });
        }
    }
}
  • Cấu hình ghi chú cho API

    1.png

    • Thêm đường dẫn
using GetStartDemo.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace GetStartDemo
{
    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.AddDbContext(opt => opt.UseInMemoryDatabase("TodoList"));
            services.AddMvc();

            //Cấu hình swagger
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info{ Title = "Core API", Description = "Swagger Core API" });
                //Cấu hình tài liệu
                var xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + @"CorewithSwagger.xml";
                c.IncludeXmlComments(xmlPath);
            });

            
        }

        // 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();
            }

            app.UseMvc();

            //Cấu hình swagger
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API");
            });
        }
    }
}
  • Kết nối cơ sở dữ liệu