asp.net控制器api中的多个操作



大家好,我的控制器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();
}

关注我的WebApiConfig:

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}/",
        defaults: new { id = RouteParameter.Optional }
    );
}

当我尝试从/api/Hotel/GetDetails/访问某个方法时,会返回一条消息:"发现多个操作与请求匹配"。

谢谢和问候。

您应该对[HttpPost]和[HttpGet]使用单独的方法

您应该添加自定义路线,如下

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

希望这能帮助

相关内容

  • 没有找到相关文章

最新更新