Build Web API using Angular with ASP.NET MVC5 (Part 1)

Trong video hướng dẫn Build Angular + MVC5 vừa qua, này mình chia sẻ với mọi người, cách thiết lập các API trong ASP MVC 5, Để Angular có thể gọi được nó, trong bài này mình chia ra làm 2 phần để dễ hiểu
# Phần 1: Cấu hình các phương thức GET,POST,PUT,DELETE bên ASP MVC 5
# Phần 2: Cấu hình các tính năng để Angular có thể gọi được các phương thức được cấu hình ở phần 1
Nếu bạn đã xem qua video vừa qua hoặc chưa xem bạn có thể xem lại tại đây Build Angular + ASP MVC5
Bạn tạo cho mình file CommentController.cs trong thư mục Controlles, click right->Add->Controller->Web API 2 Controller
Sau khi tạo xong, ASP MVC 5 sẽ hiểu rằng bạn muốn thiết lập WebAPI nến nó sinh ra các tập tin mới như WebApiConfig.cs trong thưc mục App_Start
Tiếp tục bạn mở file Global.asax.cs và thêm cấu hình WebApiConfig như sau

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
namespace Angular_mvc5
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Ok vậy là cấu hình xong rồi,bạn có thể run project lên và rõ câu địa chỉ sau: https://localhost:post/api/comment xem được chưa nhé
Chúng ta nói rằng, trong model Comment.cs ta có các thuộc tính như sau(id,content,parent), vậy ta cần tạo file Comment.cs trong thư mục Models

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Angular_mvc5.Models
{
    public class Comment
    {
        public int id { get; set; }
        public string content { get; set; }
        public int parent { get; set; }
    }
}

Vậy là ta đã thiết lập model Comment xong, tiếp đó ta hãy vào thư mục Controllers/CommentController.cs mở file lên để cấu hình các phương thức GET,POST,DELETE,PUT

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Angular_mvc5.Models;
namespace Angular_mvc5.Controllers
{
    public class CommentController : ApiController
    {
        // GET: api/Comment

        List<Comment> _cmt = new List<Comment>();
        public CommentController()
        {

            _cmt.Add(new Comment() { id = 1, content = "Cmt A", parent = 0 });
            _cmt.Add(new Comment() { id = 2, content = "reply Cmt A", parent = 1 });
            _cmt.Add(new Comment() { id = 3, content = "reply Cmt A", parent = 2 });
            _cmt.Add(new Comment() { id = 4, content = "Cmt B", parent = 0 });
            _cmt.Add(new Comment() { id = 5, content = "reply Cmt B", parent = 4 });

        }

        public IHttpActionResult Get()
        {
            var data = _cmt.ToList();
            return Ok(data);
        }

        // GET: api/Comment/5
        public IHttpActionResult Get(int id)
        {
 
            var data = _cmt.Where(s => s.id == id).ToList();
            return Ok(data);
        }

        // POST: api/Comment
        public IHttpActionResult Post(Comment _data)
        {
            _cmt.Add(_data);
            var result = _cmt.ToList();
            return Ok(result);
        }

        // PUT: api/Comment/5
        public IHttpActionResult Put(int id, Comment _data)
        {
            _cmt.Where(s => s.id == id).ToList().ForEach(s => s.content =_data.content); 
            return Ok(_cmt.ToList());
        }

        // DELETE: api/Comment/5
        public IHttpActionResult Delete(int id)
        {
            _cmt.Remove(_cmt.FirstOrDefault(s => s.id == id));
            return Ok(_cmt.ToList());
        }
    }
}

+ Trong đoạn code bên trên, ta cần using Model chứa Comment, để sử dụng model của nó (using Angular_mvc5.Models)
+ List<Comment> _cmt = new List<Comment>(): tạo Mảng List chứa dữ liệu comment, sao đó khởi tạo dữ liệu mặc định cho nó. (ở đây mình không có kết nối tới SQL SERVER, các bạn có thể tự thiết lặp và kết nối)
Test API: Mình dùng Postman các bạn có thể tải về và sử dụng
+ Đầu tiền chạy project
+ Run Postman lên để test

BUILD WEB API WITH ANGULAR + ASP MVC 5BUILD WEB API WITH ANGULAR + ASP MVC 5BUILD WEB API WITH ANGULAR + ASP MVC 5BUILD WEB API WITH ANGULAR + ASP MVC 5BUILD WEB API WITH ANGULAR + ASP MVC 5

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)