The latest version of the MVC framework comes with ASP.NET Web API support and that’s great. But if like me, you’ve got a web forms website where you want to leverage the capabilities of the Microsoft Web Api, then there are some manual things you need to do.
The first question you need to ask yourself is why do you want the Web Api kit in the first place. For me, my main website runs on web form and it’s too much work at the moment to migrate it to MVC. Other new projects are being done in MVC and I need to way to communicate with the new website. For example, I’ve got a central database which stores user details and I need to get information on a particular user by querying the main website through a web service. You could very well get the same information by querying the database directly but what if you had business logic as well which filters data before it is displayed? For my problem, I needed to get the total points of a particular user by sending off the UserId.
If you right click on your ASP.NET website in Solution Explorer (Visual Studio) and click on “Add New Item”, you can select the “Web API Controller Class” which I’ve renamed as UserController:
I didn’t need all those things in the controller, so I removed all and now it looks like this:
public class UserController : ApiController { // GET api/<controller>/5 public int Get(int id) { ISession session = NHibernateSessionManager.CreateSession(); User user = new Repository<User>(session).GetById(id); NHibernateSessionManager.CloseSession(session); return user.Points; } }
But before you could actually compile your site, you need to add the following codes to your Global.ascx file:
void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } ); }
This means that if your website is http://www.mydomain.com, you will be able to access your web api at http://www.mydomain.com/api and in my case for my controller it would be:
http://www.mydomain.com/api/user/5 where 5 is the UserId of the user I want to retrieve the points for.
It was as simple as this and I couldn’t believe it.
How to call the Web API url in code
In order to consume the web api, you can use the HttpClient class. For example in my MVC project, I added the following method:
int _points; public void GetUserPoints(int userId) { try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiUrl"]); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(String.Concat("user/", userId)).Result; // Blocking call! if (response.IsSuccessStatusCode) { // Parse the response body. Blocking! _points = response.Content.ReadAsAsync<int>().Result; } } catch (Exception ex) { _points = 50; } }
You’ll need the following namespaces for it to work:
- using System.Net.Http;
- using System.Net.Http.Headers;
Problem getting the Web Api to work on the live server
After everything was tested, I uploaded the new asp.net website which contained my web api interface onto my Windows 2008 box and I was horrified when it threw an error. It was something to do with a missing dll. It happened because the DLL was not found in the GAC while on my local machine that was the case. There are many ways to solve the problem but for me the easier thing was to install the MVC 4 framework on the Windows server to rectify the problem. And that worked!