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?
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.
vmGroup objvmGroup = new vmGroup(); string apiUrl = ConfigurationManager. AppSettings["baseurl"] + "/Application. API/SaveObject"; var client = new HttpClient(); client. BaseAddress = new Uri(apiUrl); client.
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.
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