Answer the question
In order to leave comments, you need to log in
Why aren't MVC Controllers fired in a Web API application?
I am learning ASP.net MVC Framework.
I created an application from Web Api templates (it is the API that interests me now) according to a tutorial from Microsoft .
Now I'm trying to add standard MVC controllers to it and nothing comes out.
I created a HomeController class that inherited from Controller and put it in the Controllers folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
namespace StopSalesApi.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public String Index()
{
return "HelloWorld";
}
}
}
Previously added to the collection of routings, a route for non-Api controllers.public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// MVC routes
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{action}",
defaults: new {controller = "Home", action = "Index"}
);
}
But the MVC Framework flatly refuses to see my Home controller. Other controllers that inherit from ApiController run, but Controller descendants do not. {"Message":"Не удалось найти ресурс HTTP, соответствующий URI запроса \"http://localhost:9707/\".","MessageDetail":"Не удалось найти тип, соответствующий контроллеру \"Home\"."}
At the same time, it is worth changing the parent class of the Home type to ApiController and the framework begins to see it. Answer the question
In order to leave comments, you need to log in
Everything. Mastered at last.
In addition to using RouteTable.Routes instead of GlobalConfiguration.Configuration.Routes, you must also use the MapRoute() method instead of MapHttpRoute().
namespace StopSalesApi
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteTable.Routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" });
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
MVC controllers should be added to RouteTable.Routes (RouteTable.RouteCollection) , not GlobalConfiguration.Configuration.Routes (HttpConfiguration.HttpRouteCollection). These are different routes.
And there it will be
MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question