Web API and OData- Pass Multiple Parameters

前端 未结 2 934
生来不讨喜
生来不讨喜 2020-12-01 14:43

Is it possible to get OData to do the following? I would like to be able to query a REST call by passing on parameters than may not be the primary key. Can I call a REST met

相关标签:
2条回答
  • 2020-12-01 14:56

    You can define a function import named GetReports that has two parameters.

    (Note: the name of the function import can't be the same with entity set name)

    Configure your EDM model as:

    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();
    

    And then write your method as:

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

    Then the request

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

    will work.

    0 讨论(0)
  • 2020-12-01 14:59

    For OData v4.0 endpoints, you don't have to make it a function, you can simply do...

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

    Then you can call it like...

    /Reports(42, 2019)
    
    0 讨论(0)
提交回复
热议问题