Routing for asp.net web api with odata

My asp.net web app is a hybrid that can have all the different types of controllers -

  • asp.net MVC controllers (derived from System.Web.Mvc.Controller

    )
  • asp.ner Web-API controllers (derived from System.Web.Http.ApiController

    ) and
  • Asp.net based OData controllers (derived from System.Web.Http.OData.ODataController

    )

I'm trying to set up 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 -

  • api / Values ​​/ GetSummary (for ASP.Net Web API

    based ValuesController

    using GetSummary

    aciton method )
  • Home (for regular asp.net MVC HomeController

    )

which don't work -

  • OData / Summary
  • OData / Summary / GetSummary

My regular MVC controllers run fine, Web API controllers work fine too, but some routing doesn't work for OData controllers. Has anyone tried mixing and matching in the same app and is able to get it to work? I also need to provide the name of the action method in the route, since all action methods are mostly GET

since this is a reporting app.

+3


source to share


1 answer


Yes, you can mix all of these controllers. If MVC routing was started in Global.asax.cs first, then the default MVC route might not allow access to OData controllers. Changing the order of the rows in Global.asax.cs as shown below will solve the problem. MVC controller routing is usually configured in RouteConfig.cs, Web API and OData routing in WebAPIConfig.cs if project templates are used.



    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register); // moved up before MVC setup
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }

      

+3


source







All Articles