Tuesday 9 June 2020

Create simple Web API with ASP.NET

Step 1:- Create Database with name "TEST"

create database TEST

Step 2:- Create table Student in "TEST" database

use TEST

create table Student(

      Id int identity constraint pk_Student_Id primary key,

      Name varchar(50),

      DOB datetime,

      Gender varchar(10)

)


Lets Start


Step 1:- Open Visual Studio 2015 => Go to File Menu => New => Project...

Step 2:- Expand Visual C# from left pane => select Web => Select ASP.Net Web Application from the middle pane => Type WebApiCRUD in the Name box => Click OK


Step 3:- Select Web API template from ASP.NET Templates => Click OK


Step 4:- Open Solution Explorer => Right click on project Root(WebApiCRUD) folder => Select Add => Click New Items...


Step 5:- Expand Visual C# from left pane => select Data => Select ADO.NET Entity Data Model from the middle pane => Type StudentEntityDataModel in the Name box => Click Add


Step 6:- Select EF Designer from database => Click Next


Step 7:- Select Entity Framework 6.x Radio button => Click Next


Step 8:- Click on New Connection... to setup the database connection


Step 9:- Choose Data Source Microsoft SQL Server => Click Continue


Step 10:- Fill Connection Properties => Click OK


Step 11:- Type StudentDbContext => Click Next


Step 12:- Expand Tables => Checked Student table=> Type StudentModel => Click Finish

 

Note:- If Security Warning Message Box Prompt, checked check box and click OK button


Step 13:- StudentEntityDataModel.edmx added in the project.


Build Project


Step 14:- Right click on Controllers folder => Select Add => Click Controllers...


Step 15:- Select Web API 2 Controller with actions, using Entity Framework => Click Add


Step 16:- Select Model class => Select Data context class => Click Add



Step 17:- Student Controller code

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
 
namespace WebApiCRUD.Controllers
{
    public class StudentsController : ApiController
    {
        private StudentDbContext db = new StudentDbContext();
 
        // GET: api/Students
        public IQueryable<Student> GetStudents()
        {
            return db.Students;
        }
 
        // GET: api/Students/5
        [ResponseType(typeof(Student))]
        public IHttpActionResult GetStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }
 
            return Ok(student);
        }
 
        // PUT: api/Students/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutStudent(int id, Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
 
            if (id != student.Id)
            {
                return BadRequest();
            }
 
            db.Entry(student).State = EntityState.Modified;
 
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
 
            return StatusCode(HttpStatusCode.NoContent);
        }
 
        // POST: api/Students
        [ResponseType(typeof(Student))]
        public IHttpActionResult PostStudent(Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
 
            db.Students.Add(student);
            db.SaveChanges();
 
            return CreatedAtRoute("DefaultApi", new { id = student.Id }, student);
        }
 
        // DELETE: api/Students/5
        [ResponseType(typeof(Student))]
        public IHttpActionResult DeleteStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }
 
            db.Students.Remove(student);
            db.SaveChanges();
 
            return Ok(student);
        }
 
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
 
        private bool StudentExists(int id)
        {
            return db.Students.Count(e => e.Id == id) > 0;
        }
    }
}

All Done

API ready to consume in application


Note :- 

When consumer application not in same origin policy in that case, browsers to restrict access from one domain to resources belonging to another domain. To allow access to consumer application, enable CORS in Web API application.


Enable the CORS(Cross-Origin Resource Sharing)  

  

Step 1:- Open Solution Explorer => Right click on project Root(WebApiCRUD) folder => Click Manage NuGet Packages...

Step 2:- Search Microsoft.AspNet.WebApi.Cors => Click Install


Step 3:- Expand App_Start folder => Open WebApiConfig.cs file => Add following code

using System.Web.Http.Cors;

//Enable Core
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);

Note:- 
Enable CORS in Controller level, decorate controller with EnableCors attribute.

using System.Web.Http.Cors;
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class StudentsController : ApiController
{
    private StudentDbContext db = new StudentDbContext();

No comments:

Post a Comment