Homayoun Behzadian
Homayoun Behzadian

Reputation: 1163

How an asp.net becomes MVC or WebApi?

I'm trying to choose between MVC and WebApi, so some situations WebApi is better (documentation, testing and ...) and for some situation MVC controllers are better (when rendering Razor pages and so on)

But when I create an asp.net MVC webapplication, none of controllers inhertited from ApiController will be detected and If I create an asp.net WebApi web application, none of Controllers inheriting from System.Web.Mvc.Controller will be detected.

I compared web.config of these 2 web apps, nothing is different.

I have 2 questions

  1. If both web.config are same, then how one app detects only controllers inherit from System.Web.Mvc.Controller and another app detects only controllers inherit from ApiController? what's different between them?

  2. Can I configure web app to support both controller types?

Upvotes: 1

Views: 152

Answers (2)

DAVID OLASUPO
DAVID OLASUPO

Reputation: 39

If you right click and "go to definition" of both controllers you will discover they are of different namespaces and even implement different base classes, so you won't be able to have a class inherit from both "ApiController" (Web-Api) & "Controller"(MVC) at the same time (I much as I know).

However, if you need both controllers in the same projects, you can just right-click and add either a "Web-Api" controller or "MVC controller".

And then you can actually instantiate and use the "Web-Api" controller on the MVC controller code

Upvotes: 1

Hossein
Hossein

Reputation: 3113

The steps You needed to perform were:

1- Make Mvc Web Application Add reference to System.Web.Http.WebHost.

2- Add App_Start\WebApiConfig.cs (see code snippet below).

3- Import namespace System.Web.Http in Global.asax.cs.

4- Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs), before registering the default Web Application route as that would otherwise take precedence.

5- Add a controller deriving from System.Web.Http.ApiController.

I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

App_Start\WebApiConfig.cs:

using System.Web.Http;

class WebApiConfig
{
    public static void Register(HttpConfiguration configuration)
    {
        configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });
    }
}

Global.asax.cs:

using System.Web.Http;

...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    WebApiConfig.Register(GlobalConfiguration.Configuration);
    RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.

Upvotes: 0

Related Questions