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.
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.
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);
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); }
4. Finally, let’s test the API.
Note: you can test an API using a tool named Postman.
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); } }
Share your love with us 😉
Click on a star to rate it!
Average rating 5 / 5. Vote count: 1
No votes so far! Be the first to rate this post.