Create RESTful Web API with ASP.NET MVC in Visual studio 2017

3 minute(s) reading

Problem

How to create, build or setup RESTful Web API’s in an existing ASP.NET MVC Web Application project using Visual studio 2017

Final output

After completing this article you would be able to make a Web API in ASP.NET MVC project and get a response from it as a JSON.

Assuming you forgot to add a Web API into your ASP.NET MVC project while creating a project.

Then what do you need to do add Web API and get it working.

Let’s get started 🙂

Solution

1. Create a folder named ‘Api’ inside Controller folder.
Select a web api 2 controller while creating it.

Select web api 2 Controller
Create Web API controller

Now you will notice that a readme.txt file generated which tells you how to setup API for you project.

Also, you can see that it generate a WebApiConfig.cs file inside App_start folder.

readme.txt file generated also webapiconfig.cs file insdie App_start folder
readme.txt file

2. Follow the instructions given in readme.txt file.
2-1. Add the following namespace references in Global.asax.cs file:

using System.Web.Http;
using System.Web.Routing;

2-2. If the code does not already define an Application_Start method, add the following method in Global.asax.cs file:

protected void Application_Start()
{
}

2-3.  Add the following lines at the beginning of the Application_Start method in Global.asax.cs file:

GlobalConfiguration.Configure(WebApiConfig.Register);
Configure global.asax file similar to the instructions given in readme.txt file
Setup readme.txt file instructions

3. Let’s add a simple method inside our Api controller which will return list of donators

// Get /api/donators
public IHttpActionResult GetDonators()
{
    var listOfDonators = DBContext.Donators.ToList();

    return Ok(listOfDonators);
}
Add method to Api controller to get list of donators
Add Web API method to get list of donators

4. Finally, let’s test the API.
Note: you can test an API using a tool named Postman.

Api test
Web API response in XML format

Congratulations now your project has been setup for Web API using ASP.NET MVC project 🙂

Note: By default Api returns data in XML format to change it to JSON for all the request you can add the below lines at the end on  Register method inside your WebApiConfig.cs file

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...
        
        // XML to JSON Api response for all Api calls
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
    }
}
Convert api response from XML to JSON
Convert Web api response from XML to JSON

Leave a Reply