Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - Web API and OData- Pass Multiple Parameters

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 method like --> GetReports(22, 2014) or 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));
}

Here is my latest change.

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

my method for controller 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());

            }

I tried calling the url like:

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

No HTTP resource was found that matches the request URI 'http://localhost:6064/odata/Reports(key%3D5%2Cyear%3D2014)/ListReports'.`

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...