我尝试在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/entries
和https://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."
从[ApiController]
继承时,不需要使用ODataController
注释。删除注释,它应该按预期工作。为了能够使用$take
进行查询,您需要设置它:
app.UseMvc(b =>
{
b.Take();
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
您还可以添加其他操作,例如Select().Expand().Filter().OrderBy().MaxTop(100).Count()