我想做的主要事情是我希望我的 AspNet.Core 3.1 API 支持 Odata。主要的是 WebApi 公开了 Dto 对象,该对象在内部映射到实体对象。我已经实施了更改,但是不断收到 404 错误。我所做的改变是:
安装 AspNetCore.OData 7.3。
添加了对 Startup.cs 的更改
public class Startup { public void ConfigureServices(IServiceCollection services) services.AddOData(); services.AddMvc(options => options.EnableEndpointRouting = false);
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
IEdmModel model = GetEdmModel();
app.UseMvc(builder =>
{
builder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
builder.MapODataServiceRoute("odata", "odata", model);
});
public static IEdmModel GetEdmModel()
{
if (_edmModel == null)
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<CustomerDto>("CustomerDtos");
_edmModel = builder.GetEdmModel();
}
return _edmModel;
}
- 客户控制器更改
public class CustomersController : ControllerBase
{
public ICustomerRepository _customers;
public CustomersController(DbContext context)/
{
_customers = new CustomerRepository(context);
}
[HttpGet]
[EnableQuery]
public async Task<ActionResult<IEnumerable<CustomerDto>>> Get()
{
return Ok((await _customers.GetCustomers()).Select(c=>CustomerDto.MapToCustomerDto(c)));
}
}
然而,这不断给 404 错误 odata/customers
如果使用 url /odata/customers
,则customers
指的是名为 的实体集Customers
。控制器名称始终源自 OData 路径根部的实体集。
解决方案:
一种方法是保留 EntitySet 名称但修改控制器名称
(CustomersController->CustomerDtosController ):
public class CustomerDtosController : ControllerBase
网址: /odata/customerDtos
另一种方法是保留控制器名称但修改EntitySet
名称:
builder.EntitySet<CustomerDto>("Customers");
网址: odata/customers
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句