I'm working on a large ASP.NET MVC/Web API project and wanted to separate out the controllers into their own project (as described in this article http://msdn.microsoft.com/en-us/magazine/jj190803.aspx). The difference is that I'm needing to separate out the ASP.NET Web API controllers, not “normal” MVC controllers.
In my solution, I have two separate projects:
Anyway, I’ve seen other posts and such that haven’t really explained my exact situation, and I'm having trouble getting this solution working.
How can I break out my Web API controllers into their own separate project and use them from my HTML/JavaScript code in my separate MVC project? And, how do I call the API’s endpoints from my JavaScript/jQuery code in the separate MVC project?
Thanks.
Asp.Net Web API VS Asp.Net MVC Asp.Net MVC is used to create web applications that return both views and data but Asp.Net Web API is used to create full-blown HTTP services with an easy and simple way that returns only data, not view.
It shouldn't! That's why it's designed in a modular way. In most web applications out there, we version and deploy all these assemblies (Web, BLL and DAL) together. So, separating a project into 3 projects does not add any values.
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.
Since your Web Api and MVC are in different projects and probably they will run in different domains making the communication little difficult from client-side beause of cross-domain issue.
Though you can try JSONP or CORS but they are not going to be much useful (one is a hack and the other is not widely supported in browsers) and so you have to create wrapper MVC controllers in your MVC project that will talk to the Web Api through HttpClient
class.
Your javascript will make calls to your MVC controllers and this way you can avoid the cross domain issues.
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