简体   繁体   中英

Web Api routing to action with string paramater

It seems simple like in ASP.NET MVC but I can't figure out how to map an URI with a string parameter to an action on my controller. So I have three actions in my controller as below:

 //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);
    }

So I would like to map an URI with the action:

GetSocieteByLibelle(string name)

My route configuration is the default one for Wep API project. May someone explain me how to map an URI to that action ? Thanks in advance !

Looks like the two routes are resulting in the same method call being invoked. Try putting a [Route] attribute on one of them as follows:

[Route("api/Societe/libelle/{name}")]
public IHttpActionResult GetSocieteByLibelle(string name)
{

}

Note that the default /api/Societe/{id} should still hit your first Action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM