you should use use separate methods for [HttpPost] and [HttpGet]
Multiple actions in asp.net controller api
-
27-06-2022 - |
سؤال
Hello People I have 2 methods inside in my controller api:
[HttpPost]
[HttpGet]
public IEnumerable<Hotel> Get(HotelSearch hotelSearch)
{
try
{
if (hotelSearch == null)
{
hotelSearch = new HotelSearch
{
Rooms = new List<RoomSearch> { new RoomSearch { AdultsQuantity = 1, ChildrenQuantity = 0 } },
Stars = 0,
City = "MIA",
IsoCountry = "US",
DepartureDate = Convert.ToDateTime("10/10/2013"),
ArrivalDate = Convert.ToDateTime("17/10/2013")
};
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return HotelService.GetHotel(hotelSearch);
}
[HttpPost]
[HttpGet]
public Hotel GetDetails(Hotel hotel)
{
//return HotelService.GetHotelDetails(hotel);
return new Hotel();
}
Follow my WebApiConfig:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}/",
defaults: new { id = RouteParameter.Optional }
);
}
When I try to access some method from /api/Hotel/GetDetails/, an message is returned: "Multiple actions were found that match the request".
Thanks and regards.
المحلول
نصائح أخرى
You should add Custom route like below
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Hope this helps
لا تنتمي إلى StackOverflow