How To Make Rest API In .NET Framework MVC

REST means “Representational State Transfer” and API means Application Programming Interface.

Why do we use API?

We use API to provide data to our application, it could be web apps, mobile apps, or any desktop app. The application makes a request to the API and the API from the database provides the required data to the application in the form of JSON or Xml, and the application then displays that data to the user.

API in MVC is not much different from MVC Web apps, as API provides JSON or XML data to the user and Web app provides a view to the user.

My focus is on the beginners, who want to learn and explore their talent. Now, let us start building an API in MVC .NET Framework.

  1. First, create new project in VS.



  2. Now, select Web API.



  3. VS will start creating the project for you.



  4. After creating the project, this screen will display, as shown below.



  5. Now, go in the ValuesController : APIController and you will see it is inherited from APIController. Now, focus on Get method.
    1. Comment this line first //[Authorize]  
    2. // GET api/values  
    3. public IEnumerable < string > Get() {  
    4.     return new string[] {  
    5.         "value1",  
    6.         "value2"  
    7.     };  
    8. }   

    This method will return an array to the user, which will contain the data of values.

    Now, run the Application and put this URL in the Browser.

    http://localhost:53412/api/values

    The Browser will show you this result.


    This was the built in method of .NET API, so that the native developers can learn it easily.

  6. Let's create own API now. In the Models, create a class named Employee.

    In this class, give properties of employee and create another class named Employees in the same namespace and create a list of Employees. Here, the screen shot of the class is given below.



    Now, change the controller


  7. Now, run the application and browse or refresh the same URL.


     At the beginning, I mentioned that we can get the information from the database too. I used a hardcoded list to make you understand how an API works.

Your suggestions and feedback will be appreciated. Learn and share.

Next Recommended Reading Login Page In MVC Using Entity Framework