Create MVC Web API

What is ASP.NET Web API?

                     ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients including browsers, phones and tablets. You can use XML or JSON or something else with your API. JSON is nice for mobile apps with slow connections, for example. You can call an API from jQuery and better utilize the client's machine and browser.

                       In this article we will show the basic database operations (CRUD) in an HTTP service using ASP.NET Web API. Many HTTP services also model CRUD operations through REST or REST-like APIs.


1. Create Web API Project
  • Open Visual Studio and create "New Project" i.e. File -> New Project.
  • Choose "ASP.NET MVC 4 Web Application" template and name project as "WebApplication1".
  • When you click "OK" button, a new window will appear for selecting a sub-template. Actually for ASP.NET MVC 4 Web Application, we have multiple sub-options i.e. Empty, Internet Application, Web API etc.
  • Choose "Web API" and simply press "OK" button.





2. Adding Controller Class

                         Controller class plays an important role, because request coming from client hits the controller first. Then the controller decides which model to use to serve the incoming request. So, in order to add a controller:


  • Right click on the "Controller" folder and choose "Controller" under "Add" from the context menu as shown in figure.
  • Name the controller as "nameController".




Code:

    I Already create the Edmx for my project as bloggerEntities and my Table name is tNames.


        WebApplication1.bloggerEntities dc = new bloggerEntities();

        public object GetName()
        {
            var Namelist = dc.tNames.ToList();
            return Request.CreateResponse(HttpStatusCode.OK, new { HttpCode = "200", Status = "success", Message = "SuccessFully Listed", details = Namelist });
           
        }



Now, it's time to test your HTTP service using ASP.NET MVC Web API.
Run the application by pressing "CTRL+F5", Welcome window will appear.
 change the URL as "http://localhost:XXXX/api/name/GetName". You will see the results as shown in following output window.



or You Can  use External Tool PostMan App





Result:
{
  "HttpCode": "200",
  "Status": "success",
  "Message": "SuccessFully Listed",
  "details": [
    {
      "ID": 1,
      "Name": "Fiera"
    },
    {
      "ID": 2,
      "Name": "Lenn"
    },
    {
      "ID": 3,
      "Name": "Menny"
    }
  ]
}




Comments

Popular posts from this blog

Unable to perform operation on the item is locked in workspace

Maximum Stored Procedure Function Trigger or View Nesting Level Exceeded (limit 32) in SQL Server

Insecure cookie setting: missing Secure flag