Search code examples
c#asp.netasp.net-web-apiodata

Web API OData v4 only gives 404


I'm at the end of my rope, I've run out of things to Google. I don't know which piece of the below could be wrong?

localhost:29197/odata/Tests/ returns 404

localhost:29197/odata?$metadata returns 404 (or is it localhost:29197/odata/$metadata)

Same 404 with or without the route prefix.

Controller:

namespace MvcApplication.Api
{
    public class TestsController : ODataController
    {
        [EnableQuery]
        public IQueryable<Test> Get()
        {
            return new List<Test>() {new Test() {Id = 1}}.AsQueryable();
        } 
    }
}

WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.MapODataServiceRoute(routeName: "odata", routePrefix: "odata", model: GetEdmModel());
    }

    private static IEdmModel GetEdmModel()
    {
        var builder = new ODataConventionModelBuilder();

        builder.EntitySet<Test>("Tests");

        var model = builder.GetEdmModel();
        return model;
    }
}

WebApiConfig.Register comes before RouteConfig.RegisterRoutes

The Web.config contains <modules runAllManagedModulesForAllRequests="true" />


Solution

  • Just make sure that, you have registered WebApi conffig in Application start event in global.asax.cs like below -

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }