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

时间:2013-09-04 18:19:34

标签: c# asp.net-mvc asp.net-apicontroller

Hello People我的控制器api中有2个方法:

[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 /访问某些方法时,会返回一条消息:“找到了与请求匹配的多个操作”。

谢谢和问候。

2 个答案:

答案 0 :(得分:4)

你应该使用[HttpPost]和[HttpGet]

的单独方法

答案 1 :(得分:0)

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

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

        }

希望这有帮助