All Links I find talk about using an Web API inside a mvc project.
But I want the opposite.
I can not find any info about that scenario and how to integrate mvc into a web api project.
Is it possible at all?
All Links I find talk about using an Web API inside a mvc project.
But I want the opposite.
I can not find any info about that scenario and how to integrate mvc into a web api project.
Is it possible at all?
I'm starting these instructions from an empty ASP.Net project setup with Web API.
Install the Microsoft.AspNet.Mvc
Nuget package.
Set up MVC routes and any other MVC configuration in your global.asax, where you configure Web API. You can do this configuration in a separate class and call it from global.asax, if you wish.
Example:
RouteTable.Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Add an MVC controller to a controllers
folder. This should be a separate folder that houses your Web API controllers, and does not have to be called controllers
.
Create a Views
folder. To make this a lot easier and less time consuming, create an MVC project in a throwaway solution and copy its Views
folder over. In particular, you want to copy over any files in the Views\Shared
folder, and all .config
files inside the Views
folder. Without these, your MVC views won't work.
If you created a throwaway project for #4, look through its web.config, in particular, at the <system.web>
settings.
If you didn't, here's part of mine:
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
You should now have MVC working in a ASP.Net project alongside Web API.
For more organization, you can create an MVC Area. To get started you don't need Areas, and if you decide later to add Areas, it's easy to move existing MVC code into one or more new Areas.
For more information, read this blog post by David Paquette. Yes, the article is about Web Forms, but the instructions and concepts are congruent. Plus, Web Forms is just an ASP.Net project with Web Forms, just like Web API.
It's simple and I use it on several sites - create a new Area (I use 'UI') and treat it as a simple MVC site.
You will have to fix your default routes per this: Multiple types were found that match the controller named 'Home'