Delphi.Boy
Delphi.Boy

Reputation: 1216

MVC and Web API Projects in the same Solution

I created a solution a while ago that contains a Web API 2 project (provides JSON data to mobile devices) and a Class Library (includes my data access services).

The Web API project uses Ninject for DI and everything works fine.

Now I need to add a separate MVC project for a few web pages. The api should be accessible from www.example.com/api/controller, while the website should be accessed through www.example.com/controller.

The problem is that each of these two, has a different "Register" method with seemingly incompatible route collections. If I set the MVC project as the startup project, routes for the api are not registered, and vice versa. If I set "Mutiple startup projects", they run on different ports which is not my cup of tea.

How I can set the MVC project as the startup project, while registering all routes for both of them?

One more thing. Because the Web API project was created sooner, Ninject configuration has been written inside it. Of course, some of the services from the Class Library project are needed inside the new MVC project. Do I have to move Ninject configuration to the MVC project, or they just work because they are run on startup of the Web API Project?

Upvotes: 8

Views: 14094

Answers (2)

adricadar
adricadar

Reputation: 10209

This 2 projects are independent from each other like 2 different applications even if they are in the same solution.

To succeed what you try to achieve you have to:

1) Deploy your MVC project to www.example.com (main virtual application).

2) Deploy your WebAPI project to www.example.com/api (api folder is a virtual application). Don't forget to remove api from your WebAPI routes (other wise you have to use this route www.example.com/api/api/controller).

Doing this you can acces independently both projects in the same url.

For NInject part, you can register again the services in the MVC project. Another solution will (which i recommend) be to make a class library project and register there the services after that you reference this class library in both projects.

Upvotes: 15

janhartmann
janhartmann

Reputation: 15003

What I like to do, is to have the MVC and WebAPI project in two separate projects (separation of concerns) but let them share the same business logic.

I like to utilize the Command and Query pattern. So all commands and queries is located in another solution project, which both the MVC and WebAPI project has access to.

I deploy the MVC project on the www.domain.com path, the WebAPI project on the api.domain.com and enable CORS on WebAPI for the www origin.

Upvotes: 3

Related Questions