如何在ASP.NET Core 2.1中使用OData?

问题描述 投票:-1回答:1

我尝试在ASP中使用OData。我的代码:

//============== 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();
    }

控制者:

[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();
    }

背景情况:

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

但是,我不清楚,我应该用什么路径来获取条目(没有OData我会使用localhost:9000/api/entries,但现在我很困惑)。

我试图做https://localhost:44384/odata/entrieshttps://localhost:44384/odata/api/entries,但我得到404

我试着评论控制器的路线,就像这样

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

并且还修改了动作

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

我尝试了https://localhost:44384/odata/Entries和gotthe条目的完整列表...然而,https://localhost:44384/odata/Entries?$take=2不起作用:400 Bad Request:Parameter name: $take' is not supported."

asp.net-web-api asp.net-core odata asp.net-core-webapi asp.net-core-2.1
1个回答
1
投票

[ApiController]继承时,不需要使用ODataController注释。删除注释,它应该按预期工作。为了能够使用$take进行查询,您需要设置它:

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

您还可以添加其他操作,例如Select().Expand().Filter().OrderBy().MaxTop(100).Count()

© www.soinside.com 2019 - 2024. All rights reserved.