Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Wednesday, 2 September 2020

Read text from a file in Web API

 using System.Web;


string path = Path.Combine(HttpRuntime.AppDomainAppPath, "TextFile\\Results.txt");

string dataText = File.ReadAllText(path);

Thursday, 13 August 2020

Dependency Injection in ASP.NET Web API 2

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

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type WebApi in the Name box => Click OK

Step 4: - Select Empty template from ASP.NET Templates List and Checked Web API check box => Click OK

Step 5: - Project Structure


Step 6: - Right Click on Project Root folder in Solution Explorer => Add => Click on New Folder => Type folder name Repository

Step 7: - Right Click on Repository folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Interface from middle pane => Type ITest.cs in the Name box => Click Add

Step 8: - Add following code in ITest.cs file  

namespace WebApi.Repository
{
    public interface ITest
    {
        string GetMessage();
    }
}

Step 9: - Right Click on Repository folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type Test.cs in the Name box => Click Add

Step 10: - Add following code in Test.cs file

Note:- Here Test.cs implement the ITest.cs interface

namespace WebApi.Repository
{
    public class Test : ITest
    {
        public string GetMessage()
        {
            return "Welcome to Web Api.";
        }
    }
}

Step 11: - Right Click on Controllers folder => Add => Controller... => Select MVC 5 Controller - Empty => Click Add => Type HomeController in Controller name box => Click Add

Step 12: - Add following code in HomeController  file

Note:- Here we have create parameter-less HomeController  constructor to initialize the object of Test class to call the GetMessage().

using System.Web.Http;
using WebApi.Repository;
 
namespace WebApi.Controllers
{
    public class HomeController : ApiController
    {
        private readonly ITest _test;
        public HomeController()
        {
            _test = new Test();
        }
        [HttpGet]
        public string Index()
        {
            return _test.GetMessage();
        }
    }
}

We have done the simple Web Api project without using Dependency injection(DI).

Launch the project => Enter URL in browser.

http://localhost:51896/api/home/index

Note:- Port defer from system to system. Check your Port.

Till here our project work as expected. Now implement the Dependency injection(DI) in it.

Step 13: - Open HomeController file and change HomeController constructor and inject the service.

using System.Web.Http;
using WebApi.Repository;
 
namespace WebApi.Controllers
{
    public class HomeController : ApiController
    {
        private readonly ITest _test;
        public HomeController(ITest test)
        {
            _test = test;
        }
        [HttpGet]
        public string Index()
        {
            return _test.GetMessage();
        }
    }
}

Launch the project => Enter URL in browser.

http://localhost:51896/api/home/index

Note:- This time we will received an error “An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor.”


This error indicates that Web Api by default not support the parameterized constructor and DI. For that we need to use one of Unity library to fix this issue.

Step 14: - Open Solution Explorer => Right Click on References => Click on Manage NuGet Packages… => Search Unity.AspNet.WebApi => Choose Unity.AspNet.WebApi from list => Click to Install



Step 15: - Open Solution Explorer => Expand App_Start folder 

Note:- Here 2 file added in when we install the Unity.AspNet.WebApi DLL that is UnityWebApiActivator.cs and UnityConfig.cs

Step 16: - Open UnityConfig.cs => Go to RegisterTypes function => Do the following changes

Launch the project => Enter URL in browser.

http://localhost:51896/api/home/index

Here we have successfully implemented the Dependency injection(DI) in our Web Api project. 

To read setting from web.config file we need to add one more package Unity.Configuration in our solution.

Step 17 : - Open Solution Explorer => Right Click on References => Click on Manage NuGet Packages… => Search Unity.Configuration => Choose Unity.Configuration from list => Click to Install



Step 18: - Open Web.config file => Add following code in your configuration section

<configSections>
  <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <alias alias="ITest" type="WebApi.Repository.ITest, WebApi" />
  <alias alias="Test" type="WebApi.Repository.Test, WebApi" />
  <containers>
    <container>
      <register type="ITest" mapTo="Test"/>
    </container>
  </containers>
</unity>

 

Step 19: - Open UnityConfig.cs => Go to RegisterTypes function => Do the following changes

Launch the project => Enter URL in browser.

http://localhost:51896/api/home/index

ALL Done

 

 

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