我正在尝试为客户实现一个ODataController,它能够为我提供uri来查询模型
http://localhost:1234/odata/v1/customers?$top=4
或使用以下代码根据ID吸引一位客户
http://localhost:1234/odata/v1/customers/1
但是无论我如何尝试,我都无法将参数传递给控制器上的动作/功能。
我的代码是这样的。
app.UseMvc(routeBuilder =>
{
routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
routeBuilder.MapODataServiceRoute("ODataRoutes", "odata/v1", modelBuilder.GetEdmModel(app.ApplicationServices));
routeBuilder.EnableDependencyInjection();
});
GetEdmModel
基本上是在建立这样的模型:
builder.EntitySet<Customer>("Customers")
.EntityType
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select()// Allow for the $select Command;
.ContainsMany(x => x.Transactions)
.Expand();
在控制器本身上,我定义了属性路由
[Produces("application/json")]
[ODataRoutePrefix("v1/[controller]")]
public class CustomersController : ODataController
{
[EnableQuery]
public ActionResult<IQueryable<Customer>> GetCustomers()
{
try
{
return context.Set<Customer>();
}
catch (Microsoft.OData.ODataException ex)
{
return BadRequest(ex.Message);
}
}
[EnableQuery]
public ActionResult<Customer> Get([FromODataUri] string id)
{
try
{
var customer = context.Set<Customer>().Where(r => r.CustomerId == id).SingleOrDefault();
我看到当我拥有uri = http://localhost:1234/odata/v1/customers/1
时,它会传递给函数Get([FromODataUri] string id)
,但是id的值始终为null。我曾尝试定义[ODataRoute("{id}")]
,但即使这样也没用。
答案 0 :(得分:0)
OData使用控制器名称。
将[ODataRoutePrefix("v1/[controller]")]
更改为[ODataRoutePrefix("v1/Customers")]
将string id
更改为string key