Web API和OData-传递多个参数

时间:2014-07-07 17:12:06

标签: c# odata asp.net-web-api2

是否可以让OData执行以下操作?我希望能够通过传递可能不是主键的参数来查询REST调用。 我可以调用REST方法,例如 - > GetReports(22, 2014)Reports(22, 2014)

[HttpGet]
[ODataRoute("Reports(Id={Id}, Year={Year})")]
public IHttpActionResult GetReports([FromODataUri]int Id, [FromODataUri]int Year)
{
    return Ok(_reportsRepository.GetReports(Id, Year));
}

这是我最近的更改。

  //Unbound Action  OData v3
       var action = builder.Action("ListReports");
        action.Parameter<int>("key");
        action.Parameter<int>("year");
        action.ReturnsCollectionFromEntitySet<Report>("Reports");

我的控制器ReportsController方法

[HttpPost]
            [EnableQuery]
             public IHttpActionResult ListReports([FromODataUri] int key, ODataActionParameters parameters)

            {

                if (!ModelState.IsValid)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }


                int year = (int)parameters["year"];
                return Ok(_reportsRepository.GetReports(key, year).Single());

            }

我尝试调用网址:

 http://localhost:6064/odata/Reports(key=5,year=2014)/ListReports

未找到与请求URI匹配的HTTP资源&#39; http://localhost:6064/odata/Reports(key%3D5%2Cyear%3D2014)/ListReports'。“

2 个答案:

答案 0 :(得分:27)

您可以定义一个名为GetReports的函数导入,它具有两个参数。

(注意:函数导入的名称与实体集名称不一致)

将您的EDM模型配置为:

var builder = new ODataConventionModelBuilder();
builder.EntitySet<Report>("Reports");
var function = builder.Function("GetReports");
function.Parameter<int>("Id");
function.Parameter<int>("Year");
function.ReturnsCollectionFromEntitySet<Report>("Reports");
var model = builder.GetEdmModel();

然后将您的方法编写为:

[HttpGet]
[ODataRoute("GetReports(Id={Id},Year={Year})")]
public IHttpActionResult WhateverName([FromODataUri]int Id, [FromODataUri]int Year)
{
    return Ok(_reportsRepository.GetReports(Id, Year));
}

然后请求

Get ~/GetReports(Id=22,Year=2014)

会奏效。

答案 1 :(得分:1)

对于OData v4.0端点,您不必使其具有功能,只需执行...

public class ReportsController : ODataController
{
    [EnableQuery]
    [ODataRoute("Reports({id}, {year})")]
    public IQueryable<ReportModel> Get([FromODataUri] int id, [FromODataUri] int year)
    {
        ...
    }
}

然后您可以将其命名为...

/Reports(42, 2019)