My asp.net web application is hybrid which can have all different types of controllers -
System.Web.Mvc.Controller
)System.Web.Http.ApiController
) andSystem.Web.Http.OData.ODataController
)I am trying to configure routing in WebApiConfig.cs
for Web API and OData controllers and it looks something like this -
public static void Register(HttpConfiguration config)
{
config.Routes.MapODataRoute("OData", "odata", CreateEdmModel());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
}
public static IEdmModel CreateEdmModel()
{
ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Detail>("Details");
return modelBuilder.GetEdmModel();
}
routes that work -
ASP.Net Web API
based ValuesController
with GetSummary
aciton method)HomeController
)routes that doesnt work-
My regular MVC controllers execute fine, Web API controllers also work fine, but somehow routing is not working for OData controllers. Has anyone tried mix and match in a single application and able to make it work? I will also need to specify action method name in the route, since all action method are mostly GET
since it is a reporting application.
Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes.
The Routing of Web API OData is derived from Web API Routing and adds more extensions. In Web API OData, an OData controller (not API controller) serves as the request handler to handle HTTP requests, while the public methods (called action methods) in the controller are invoked to execute the business logic.
In this article How to create OData endpoints in ASP.NET Web API for ASP.NET 4. x. OData is a data access protocol for the web. It provides a uniform way to query and manipulate data sets. Web API supports both Version 3 and Version 4 of the OData protocol.
Yes, it is possible to mix all these controllers. If MVC's routing was activated first in Global.asax.cs then MVC's default route may not allow to reach OData controllers. Changing the order of lines in Global.asax.cs as shown below will solve the issue. MVC controllers routing is usually setup in RouteConfig.cs , Web API and OData routing in WebAPIConfig.cs if project templates were used.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register); // moved up before MVC's setup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
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