Can i have asp.net core mvc and web api as single project

john john 946 Reputation points
2022-10-17T22:52:45.517+00:00

We want to build an asp.net core web application. it contains MVC part for returning Views and API to return JSON and have Restful services for our web application.

So can I have MVC and Web API inside the same project? as currently when i want to create a new project inside .NET 6.0 i have to select the either MVC or Web API type :-

251341-image.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,240 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. SurferOnWww 2,071 Reputation points
    2022-10-18T00:21:59.017+00:00

    So can I have MVC and Web API inside the same project?

    Yes, you can simply add the controller for the ASP.NET Core Web API in the existing Controllers folder. You do not have to add the Web API project.

    0 comments No comments

  2. Zhi Lv - MSFT 32,046 Reputation points Microsoft Vendor
    2022-10-18T02:00:09.41+00:00

    Hi @john john ,

    can I have MVC and Web API inside the same project? as currently when i want to create a new project inside .NET 6.0 i have to select the either MVC or Web API type

    Yes, you can add them in the same project.

    The easiest way is to use the "ASP.NET Core Web App (Model-View-Controller)" template to create the project, then you can add the API controller in the Controllers folder.

    Right click the Controllers folder, select Add => Controller option, then in the popup window, select the API controller:

    251354-image.png

    By using this method, in the program.cs file, it already configured the MVC routing, and for the API controller, it will use the [Route] attribute to configure the endpoint.

    If you are using the "ASP.NET Core Web API" template to create the project. In the project, it only contains the Controllers folder, and the in the Program.cs file it only configure the routing for the Controller, without the view.

    251299-image.png

    So, in this scenario, you have to add the Models and Views folder, add the Layout page and so on (refer to the new MVC application) by yourself. And in the Program.cs file, you have to configure the MVC route.

    So, I suggest you can use the "ASP.NET Core Web App (Model-View-Controller)" template to create the project, and then add the API controller in the Controller folder.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments