Search code examples
asp.net-web-apiasp.net-coreodataasp.net-core-webapiasp.net-core-2.1

How to use OData in ASP.NET Core 2.1?


I try to use OData in an ASP. Bellow my code:

//============== Startup.cs
public void ConfigureServices(IServiceCollection services) {
    services.AddDbContext<EntriesContext>(
        opt => opt.UseMySql("server=localhost;database=mydb;user=myusr;password=mypass",
        mysqlOptions =>{mysqlOptions.ServerVersion(new Version(5..), ServerType.MySql);}));

    services.AddOData();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    ...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        ...
        app.UseMvc(b => { b.MapODataServiceRoute("odata", "odata", GetEdmModel()); });
    }

    private static IEdmModel GetEdmModel() {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Entry>("Entries");
        return builder.GetEdmModel();
    }

The Controller:

[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowMyOrigin")]
public class EntriesController : ODataController
{
    private readonly EntriesContext _context;

    public EntriesController(EntriesContext context) {
        _context = context;
    }

    [HttpGet]
    [EnableQuery]
    public ActionResult<List<Entry>> GetAll() {
        return _context.Entries.ToList();
    }

And the context:

public class EntriesContext : DbContext
{
    public EntriesContext(DbContextOptions<EntriesContext> options) : base(options) { }
    public DbSet<Entry> Entries { get; set; }
}

however, is not clear for me, what path should I use to get the entries (without OData I would use localhost:9000/api/entries, but now I am confused).

I tried to do https://localhost:44384/odata/entries and https://localhost:44384/odata/api/entries but I get 404

I tried to comment the controller's route, like this

//[Route("api/[controller]")]
//[ApiController]
[EnableCors("AllowMyOrigin")]
public class EntriesController : ODataController 

and also modified the action

[HttpGet]
[EnableQuery]
public IActionResult Get() {
    return Ok(_db.Entries);
}

I tried then https://localhost:44384/odata/Entries and gotthe full list of the entries... However, the https://localhost:44384/odata/Entries?$take=2 does not work: 400 Bad Request: Parameter name: $take' is not supported."


Solution

  • You don't need to use [ApiController] annotation when you inherit from ODataController. Remove the annotation and it should work as expected. To be able to query using $take you need to setup it:

    app.UseMvc(b =>
          {
            b.Take();
            b.MapODataServiceRoute("odata", "odata", GetEdmModel());
          });
    

    You can also add other actions, e.g. Select().Expand().Filter().OrderBy().MaxTop(100).Count()