Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Host ASP.Net web api and consume from another MVC application

I am new to ASP.Net MVC and ASP.Net web api.

I have worked on Web services and cosuming them.

But I am not sure how to host ASP.Net web api and consume the same from another ASP.Net MVC application. I found some samples where people are using the api from the same project. In real world I really doubt the usage would be limited to one project.

Can some body please post some examples or links which can explain the same?

like image 268
Naresh Avatar asked Aug 08 '12 14:08

Naresh


People also ask

Can we call Web API from MVC controller?

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.

How pass data from MVC controller to Web API?

vmGroup objvmGroup = new vmGroup(); string apiUrl = ConfigurationManager. AppSettings["baseurl"] + "/Application. API/SaveObject"; var client = new HttpClient(); client. BaseAddress = new Uri(apiUrl); client.


1 Answers

Hosting ASP.NET Web API in an MVC web application makes perfect real world sense if you are mostly using the API to make AJAX type calls from your web client. Having the API and web application in the same project eliminates issues with cross-domain Ajax calls, which requires JSONP. But ASP.NET Web API can easily support JSONP if needed with a custom formatter like JsonMediaTypeFormatter available from WebApiContrib.

ASP.NET Web API makes developing REST API's easy. You use the same conventions as developing a controller in MVC. To create it separate from your web application just create an MVC 4 project and create your controllers using an ApiController instead of the standard Controller for rendering Views. Then just deploy your application just like any web application to IIS (you can also self-host ASP.NET Web API's in something like a Windows Service). Here is an example on the official ASP.NET Web API website that calls a REST API developed in ASP.NET Web API from a console application. There are many more examples on this site.

like image 76
Kevin Junghans Avatar answered Oct 12 '22 23:10

Kevin Junghans