Andrei Andrei - 1 year ago 122
ASP.NET (C#) Question

web api call get method with different url parameters

I have a set of requirements to implement the get interface:

- api/Item
- api/Item?name=test
- api/Item?updated=2016-10-12
- etc

I've defined the methods as:

- get() //returns all items
- getName([FromUri] string name)
- getUpdated([FromUri] string updated)

My issue is - if parameter doesn't exist (let's say the call was
), the
) method is called as "test" parameter mapping is not found.

I need to return the error response in this case. Is there any other proper way to read the parameters from URL to meet the interface requirement?

Answer Source

You may be looking for something like this

public class ItemsController : ApiController

    public IHttpActionResult Get()
        return Ok(new List<string> { "some results collection" });

    public IHttpActionResult GetByName([FromUri]string name = null)
        if (string.IsNullOrWhiteSpace(name))
            return BadRequest("name is empty");
        return Ok("some result");

    public IHttpActionResult GetUpdates([FromUri]string updated = null)
        if (string.IsNullOrWhiteSpace(updated))
            return BadRequest("updated is empty");
        return Ok("some result");

When you invoke these REST endpoints, you calls will look something like

GET api/items to retrieve all items

GET api/items/names/john to retrieve by name, if parameter is not supplied, error is returned

GET api/items/updated/test to retrieve updates, if parameter is not supplied, error is returned

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download