【发布时间】:2021-11-17 21:36:29
【问题描述】:
我有一个使用 C# 在 ASP.NET 5/core 之上和 EntityFrameworkCore 编写的 Web API。
我在查询数据库时使用OData 应用过滤器。
我需要手动将ODataQueryOptions 应用到我的DbSet<> 以生成分页信息。
这是我的代码
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly DbContext _db;
public ProductsController(DbContext db)
{
_db = db;
}
[HttpGet]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All, AllowedFunctions = AllowedFunctions.AllFunctions, MaxTop = 500)]
public PagedProduct Search(ODataQueryOptions<Product> queryOptions)
{
// create a query for that would count the total rows
var countQuery = queryOptions.ApplyTo(Repository.Query(), AllowedQueryOptions.Top | AllowedQueryOptions.Skip) as IQueryable<Product>;
// create a query to pull the data
var query = queryOptions.ApplyTo(Repository.Query()) as IQueryable<Product>;
var result = new PagedProduct()
{
CurrentPage = 1, // TODO get the current page value from the queryOptions
PageSize = 100, // TODO get the page size value from the queryOptions
};
result.TotalRecords = await countQuery.Count();
result.Data = await query.ToList();
return result;
}
}
但上面的代码导致 Swagger UI 失败。我收到以下错误
获取错误 未定义 /swagger/v1/swagger.json
该错误是由于在搜索操作中使用ODataQueryOptions 作为参数引起的。
如何让 Swagger UI 与 ODataQueryOptions 一起使用?
【问题讨论】:
-
您是否尝试将 Odata 特定属性添加到路由?
[ODataRoute][ProducesResponseType(typeof(ODataValue<IEnumerable<Product>>), StatusCodes.Status200OK)] -
包中不存在ODataValue
标签: c# asp.net-core swagger odata asp.net-core-webapi