我有一组实现get接口的需求:
- api/Item
- api/Item?name=test
- api/Item?updated=2016-10-12
- etc我将这些方法定义为:
- get() //returns all items
- getName([FromUri] string name)
- getUpdated([FromUri] string updated)我的问题是-如果参数不存在(假设调用是测试),get()方法就会被调用,因为找不到“测试”参数映射。
在这种情况下,我需要返回错误响应。是否有其他合适的方法从URL中读取参数以满足接口要求?
发布于 2016-10-13 03:53:05
你可能正在寻找类似这样的东西
[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");
}
}当您调用这些REST端点时,您的REST api调用将如下所示
获取接口/ items 以检索所有项
获取要按名称检索的api/items/names/john,如果未提供参数,则返回错误
获取api/items/updated/test以检索更新,如果未提供参数,则返回错误
https://stackoverflow.com/questions/40006718
复制相似问题