Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement Separate Projects for ASP.NET MVC 4 and ASP.NET Web API

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:

  • One ASP.NET MVC 4 project for serving up HTML/CSS/JavaScript (note I'm not using any standard MVC controllers, this project is all client/browser-side code that makes jQuery/Ajax calls to the Web API)
  • One ASP.NET Web API project (this project is only the ApiController(s), no views, HTML, etc., I'm still wanting the Web API project to be hosted in IIS, not self-hosted)

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.

like image 438
lmttag Avatar asked Oct 15 '12 15:10

lmttag


People also ask

Is ASP Net Web API and ASP.NET MVC same?

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.

Should you split your ASP.NET MVC project into multiple projects?

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.

How can I use my Web API project from other projects inside my solution?

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.


1 Answers

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.

like image 100
VJAI Avatar answered Oct 12 '22 19:10

VJAI