Monday, December 22, 2014

Calling ASP.NET Web API from an ASP.NET MVC Controller

In many cases, you will find examples all over the Internet on how to call ASP.NET Web API from JavaScript using a framework such as jQuery or AngularJS.  However, what if you want to call an ASP.NET Web API application directly from ASP.NET MVC?

You may ask, why would you want to do that? 

Well, the biggest reason for doing this is that it improves testability.  In order to verify that your JavaScript calls work properly, you would have to use a JavaScript Unit Testing framework and none of them integrate very nicely with Visual Studio.  In addition, JavaScript Unit Testing frameworks are not nearly as sophisticated and advanced compared to .NET/C# Unit Testing Frameworks that can use features such as Exception Handling, Mocking and Dependency Injection.

Therefore, once you have committed to calling ASP.NET Web API from your ASP.NET MVC application, how exactly do you accomplish this?

Well, fortunately, there is an article on how to do just that right here:

Though the article does not mention ASP.NET MVC directly, since MVC is simply a .NET Client to your ASP.NET Web API application, the rules still apply.  It basically just leverages the HttpClient object to get and send requests to your ASP.NET Web API application.

That is all there is to it!

1 comment: