Multiple actions were found that match the request Web API?

后端 未结 8 1211
再見小時候
再見小時候 2020-12-09 08:09

I am using web API and i am new in this. I am stuck in a routing problem. I have a controller with following actions :

    // GET api/Ceremony
    public IEn         


        
8条回答
  •  星月不相逢
    2020-12-09 08:54

    The problem here is your 2 Get methods will resolve to api/Ceremony and MVC does not allow parameter overloading. A quick workaround (not necessarily the preferred approach) for this sort of problem is to make your id parameter nullable e.g.

    // GET api/Ceremony
    public IEnumerable GetCeremonies(int? id)
    {
        if (id.HasValue)
        {
            Ceremony ceremony = db.Ceremonies.Find(id);
            return ceremony;
        }
        else
        {
            return db.Ceremonies.AsEnumerable();
        }
    }
    

    However, you would then be returning a list of ceremonies when with 1 item when your trying to query for a single ceremony - if you could live with that then it may be the solution for you.

    The recommended solution is to map your paths appropriately to the correct actions e.g.

    context.Routes.MapHttpRoute(
        name: "GetAllCeremonies",
        routeTemplate: "api/{controller}",
        defaults: new { action = "GetCeremonies" }
    );
    
    context.Routes.MapHttpRoute(
        name: "GetSingleCeremony",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { action = "GetCeremony", id = UrlParameter.Optional }
    );
    

提交回复
热议问题