使用字符串参数将Web Api路由到操作
本文关键字:Api 路由 操作 Web 字符串 参数 | 更新日期: 2023-09-27 17:58:36
这看起来很简单,就像在ASP.NET MVC中一样,但我不知道如何将带有字符串参数的URI映射到控制器上的操作。因此,我的控制器中有三个操作如下:
//GET: api/Societe
public IEnumerable<Societe> GetSociete()
{
List<Societe> listeSociete = Librairie.Societes.getAllSociete();
return listeSociete.ToList();
}
//GET: api/Societe/id
[ResponseType(typeof(Societe))]
public IHttpActionResult GetSociete(int id)
{
Societe societeRecherchee = Librairie.Societes.getSociete(id);
if (societeRecherchee == null)
{
return NotFound();
}
else
{
return Ok(societeRecherchee);
}
}
public IHttpActionResult GetSocieteByLibelle(string name)
{
Societe societeRecherchee = new Societe();
if (!string.IsNullOrWhiteSpace(name))
{
societeRecherchee = Librairie.Societes.getSocieteByLibelle(name);
if (societeRecherchee == null)
{
return NotFound();
}
}
return Ok(societeRecherchee);
}
所以我想用以下操作映射一个URI:
GetSocieteByLibelle(字符串名称)
我的路由配置是Wep API项目的默认配置。有人可以解释一下如何将URI映射到该操作吗?提前感谢!
看起来这两个路由导致调用相同的方法调用。试着在其中一个上设置一个[Route]属性,如下所示:
[Route("api/Societe/libelle/{name}")]
public IHttpActionResult GetSocieteByLibelle(string name)
{
}
请注意,默认的/api/Societe/{id}应该仍然符合您的第一个Action。