如中所述docs https://github.com/OData/AspNetCoreOData/blob/master/docs/routing-overview.md, Microsoft.AspNetCore.OData 8 使用约定将控制器绑定到实体集。他们还提供sample https://github.com/OData/AspNetCoreOData/tree/master/sample/ODataRoutingSample这表明了这种行为。
然而,我花了几个小时用一个简单的控制器设置了一个最小的 OData API,但该控制器既不由 OData 路由调试页面 ($odata) 显示,也无法通过浏览器访问。
这是模型:
namespace TestOData8
{
public class Dummy
{
public int Id { get; set; }
}
}
这是控制器:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
namespace TestOData8.Controllers
{
public class DummiesController : ODataController
{
[HttpGet]
[EnableQuery]
public IActionResult Query(CancellationToken ct)
{
return Ok(Enumerable.Range(1, 10).Select(x => new Dummy() { Id = x }).AsQueryable());
}
}
}
这段代码设置了应用程序(这是 .NET 6 的设置方式;我也尝试过 .NET 5,但没有成功):
using Microsoft.AspNetCore.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.ModelBuilder;
using TestOData8;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers()
.AddOData(opt => opt.Count().Filter().Expand().Select().OrderBy().SetMaxTop(5)
.AddRouteComponents(GetEdmModel())
);
IEdmModel GetEdmModel()
{
var bldr = new ODataConventionModelBuilder();
bldr.EntitySet<Dummy>("Dummies");
return bldr.GetEdmModel();
}
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
//app.UseAuthorization();
app.UseODataRouteDebug();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
我已经断言
- EDM 模型已注册(此 $metadata 端点显示虚拟实体)
- 控制器的名称与实体集匹配(Dummies -> DummiesController)
- 路由适用于不支持 OData 的控制器
- 设置
EnableAttributeRouting
选项为 false 不会改变行为
我错过/误解了什么?
修复方法非常简单:控制器中的方法名称必须是“Get”;更改操作名称后,控制器工作:
public class DummiesController : ODataController
{
[HttpGet]
[EnableQuery]
public IActionResult Get(CancellationToken ct)
{
return Ok(Enumerable.Range(1, 10).Select(x => new Dummy() { Id = x }).AsQueryable());
}
}
感谢@JamesLove 在另一个帖子下的小评论answer https://stackoverflow.com/a/68078863/642579.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)