I'm looking for a way to use OData controller with ASP.NET MVC4 Web.API
Route is registered in application start using
using Microsoft.Data.Edm;
using System.Web.Http;
using System.Web.Http.OData.Builder;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapODataRoute("odata", "api", GetEdmModel());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
return builder.GetEdmModel();
}
}}
OData Controller:
using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Query;
using System.Collections;
public class ODController : ODataController
{
public class Poco
{
public int id { get; set; }
public string name { get; set; }
public string type { get; set; }
}
public IEnumerable Get(ODataQueryOptions queryOptions)
{
return new Poco[] {
new Poco() { id = 1, name = "one", type = "a" },
new Poco() { id = 2, name = "two", type = "b" },
new Poco() { id = 3, name = "three", type = "c" }
};
}
Accessing url http://localhost:52216/admin/API/OD returns 406 Not accepted error. Debugger shows that controller is hit. Error occurs after returning from controller. Hwo to fix this so that OData controller can used in Web API in MVC4?
I think you mix the webapi and webapi for odata. It's better to read to the samples and tutorials first.
From your mentioned, I can't understand why you expect that OData can serialize a fly POCO list based on one empty Edm model.
Please try this:
Use your POCO class to build the model
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Poco>("Do");
return builder.GetEdmModel();
Make sure the controller class naming convention. It should be [EntitySetName] + "Controller"
Remove the Web API Route.
config.Routes.MapHttpRoute(..);
Then, the request Uri should return what you want. Thanks.