I've created a couple ASP.NET MVC applications in the past, but I've never used WebAPIs before. I'm wondering how I could create a simple MVC 4 app that does simple CRUD stuff via WebAPI instead of through a normal MVC controller. The trick is that the WebAPI should be a separate solution (and, in fact, could very well be on a different server/domain).
How do I do that? What am I missing? Is it just a matter of setting up routes to point to the WebAPI's server? All the examples I've found showing how to consume WebAPIs using an MVC application seem to assume the WebAPI is "baked in" to the MVC application, or at least is on the same server.
Oh, and to clarify, I'm not talking about Ajax calls using jQuery... I mean that the MVC application's controller should use the WebAPI to get/put data.
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.
First of all, create MVC controller class called StudentController in the Controllers folder as shown below. Right click on the Controllers folder > Add.. > select Controller.. Step 2: We need to access Web API in the Index() action method using HttpClient as shown below.
You should use new HttpClient to consume your HTTP APIs. What I can additionally advise you to make your calls fully asynchronous. As ASP.NET MVC controller actions support Task-based Asynchronous Programming model, it is pretty powerful and easy.
Here is an overly simplified example. The following code is the helper class for a sample request:
public class CarRESTService { readonly string uri = "http://localhost:2236/api/cars"; public async Task<List<Car>> GetCarsAsync() { using (HttpClient httpClient = new HttpClient()) { return JsonConvert.DeserializeObject<List<Car>>( await httpClient.GetStringAsync(uri) ); } } }
Then, I can consume that through my MVC controller asynchronously as below:
public class HomeController : Controller { private CarRESTService service = new CarRESTService(); public async Task<ActionResult> Index() { return View("index", await service.GetCarsAsync() ); } }
You can have a look at the below post to see the effects of asynchronous I/O operations with ASP.NET MVC:
My Take on Task-based Asynchronous Programming in C# 5.0 and ASP.NET MVC Web Applications
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With