3

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 api/Item?test=test), the get() 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?

3
  • Use attribute routing... Commented Oct 12, 2016 at 19:22
  • Or rethink your route design. Why not use api/Item/name/test or api/item/updated/2016-10-12? Then use a default route map followed by an error route map that handles non-matching routes. Commented Oct 12, 2016 at 19:38
  • Thanks guys for pointing into the right direction Commented Oct 12, 2016 at 20:33

1 Answer 1

8

You may be looking for something like this

[RoutePrefix("api/items")] public class ItemsController : ApiController { public IHttpActionResult Get() { return Ok(new List<string> { "some results collection" }); } [Route("names")] public IHttpActionResult GetByName([FromUri]string name = null) { if (string.IsNullOrWhiteSpace(name)) { return BadRequest("name is empty"); } return Ok("some result"); } [Route("updates")] 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, your REST api 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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi. Thank you for you reply. I've modified the method and routing slightly. The method signature is now GetByName(string name = null) and I've set the [Route("name/{name}")] attribute. It now allows to make a call as api/items/name/john. That has solved my issue. Thank you for your sample.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.