Creating Web API in MVC
To create a web api first you need to add a WEB API 2 Controller to Controller folder. When you add it you'll see a readme.txt file and do whatever it's written inside
Steps I follow :
1 - Create a class file in Models folder named "Repository.cs"
2 - Add the line below
private RmContext db;
public Repository(RmContext db)
{
this.db = db;
}
3 - Add a function
public IQueryable<AppUser> GetAllUsers()
{
return db.AppUsers;
}
4 - Go to class name with mouse, right click, Refactor -> Extract -> Extract Interfacce
5 - Select "Place Another File" and "All Public" and click Next, This creates Interface for Reporsitory
6 - Go To NuGet Manager and install Ninject MVC 5
7 - In AppStart/NinjectWebCommon.cs at the end of file add this
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IRepository>().To<IRepository>().InRequestScope();
kernel.Bind<RmContext>().To<RmContext>().InRequestScope();
}
8 - Create a Web Api 2 Controller in Controllers folder
9 - Inside this controller the code should be something like
public class LoginController : ApiController
{
private IRepository _repo;
public LoginController(IRepository repo)
{
_repo = repo;
}
public IQueryable<AppUser> Get()
{
return _repo.GetAllUsers();
}
}
10 - Go To NuGet Manager Again and install "WebApiContrib.IOC.Ninject"
11 - Go To NuGet Manager Again and install "JSON.NET"