How do I mix Web API and ASP.Net MVC pages in one project?
For instance, I have model User. I would like, within the same project, to have an ApiController that would respond to all the HTTP verbs for managing the User entities, and at the same time have a Controller that would return the appropriate strongly-typed Views depending on the Action requested.
I can't name both controllers UserController. What is the best way around this? Should I name one UserApiController and the other UserController? Any other suggestions?
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.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the . NET Framework.
- MVC, WEB API and Web Pages are merged into one single framework.
Luckily, the answer is yes. Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy. The reason for this is that the ASP.NET MVC framework has been built on top of ASP.NET.
As you can see razor pages, MVC, and Web API are working happily in a single web application. That's it for now ! Keep coding !!
In the template pane select Installed Templates and expand the Visual C# menu. Inside that Visual C# select Web. In the list of projects select ASP.Net MVC 4 Web Application. And name the project WebAPI_Basic. For reference see the following snapshot. After adding, a new dialog will pop-up.
Some core concepts of ASP.Net MVC are similar to the ASP.Net Web API such as routing and controllers. We are using Visual Studio 2012 for a demo application. Let's start with creating a Web API project.
Now let's prepare our project to use MVC. Create three folders - Models, Views, and Controllers under project's root folder. Then create Home subfolder under Views folder. Add a model class - Employee - inside Models folder.
You can put them in separate namespaces, e.g MyApp.Controllers.UsersController and MyApp.Controllers.WebAPI.UsersController.
This would let you expose similar URI routes in MVC and WebAPI, eg:
/users/1 << MVC view /api/users/1 << Web API
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