【问题标题】:How to pass multiple parameters to WebAPI Action using HttpClient.PostAsJsonAsync method?如何使用 HttpClient.PostAsJsonAsync 方法将多个参数传递给 WebAPI 操作?
【发布时间】:2013-03-11 11:28:49
【问题描述】:

我有如下 Web API 操作:

[HttpPost]
public List<FavoriteDTO> GetFavoritesPaged(long userId, PagingInfo pagingInfo)
{
  var result = _userService.GetFavoritesPaged(fav => fav.UserId == userId, pagingInfo);
  var favDTOs = ConvertToDTOs(result.Source);
  return favDTOs;
}

我需要使用 HttpClient 调用它,我正在尝试如下:

分页信息需要传递给get方法。

var pagingInfo = new PagingInfo()
{
    PageIndex = 1,
    PageSize = 10,
    OrderBy = "URL",
    OrderDirection = OrderDirection.Desc
};

OrderDirection 是一个枚举:

public enum OrderDirection
  {
    Asc,
    Desc
  }

var detailURI = "Favorites/GetFavoritesPaged?userId="+34;

HttpClient client = new HttpClient()
client.BaseAddress="mywebApiAddress";
var response = client.PostAsJsonAsync(detailURI, pagingInfo).Result;
response.EnsureSuccessCode();
var result = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result,
                                      tyepof(FavoritesDTO));

但是,它不起作用。它说内部服务器错误,我在这里缺少什么;枚举是导致问题还是其他原因?我有其他 WebAPI 工作得很好;它们都没有一个以上这样的参数。

这是我的 routConfig:

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

多参数调用WebAPI是正确的方法还是有更好的方法,请指教?

EDIT-1: 改变了这个:

 var detailURI = "Favorites/GetFavoritesPaged?userId?"+34;

到:

var detailURI = "Favorites/GetFavoritesPaged?userId="+34;

都是错字:)

EDIT-2:

使用 EDIT-1,请求转到以下 WebAPI 方法(这是错误的):

    [HttpPost]
    public FavoriteDTO AddToFavorites(FavoriteDTO favoriteDTO)
    {
      ------code to add to db------
    }

但是,当我将 routeConfig 编辑为以下内容时:

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

然后我开始收到以下异常:

ReasonPhrase: Not Found
Request: {Method: POST, RequestUri: 'http://localhost:60208/api/Favorite/GetPagedFavorites?user=1', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:{  Content-Type: application/json; charset=utf-8  Content-Length: 44}}

【问题讨论】:

    标签: asp.net-web-api dotnet-httpclient


    【解决方案1】:

    您可以尝试在控制器方法上放置一个 ActionName 属性。然后将 ActionName 附加到您的查询字符串。

    /ActionName?param=value

    【讨论】:

      【解决方案2】:

      你的网址是错误的。试试这样:

      var detailURI = "Favorites/GetFavoritesPaged?userId=34";
      

      或使用{id} 路由:

      var detailURI = "Favorites/GetFavoritesPaged/34";
      

      但是你必须修改你的参数名称:

      public List<FavoriteDTO> GetFavoritesPaged(long id, PagingInfo pagingInfo)
      

      【讨论】:

      • 刚刚更新了我的问题,正如你所指出的。及其工作。但是,您能想到更好的方法吗?而不是这样做(在 url 中添加参数)。
      • 在url中传递Id参数没有错。另一种可能性是使用视图模型并将所有内容放入 POST 正文有效负载中,然后让您的操作采用一个代表您的视图模型的参数。
      • 其实还是不行。它转到另一种方法,该方法也具有 POST 动词属性和单个参数。 [当我说它工作时,我一开始是错的,因为我没有注意到它去别的地方]。当我更改路由配置(请参阅编辑)时,它显示“未找到”。有关异常的更多详细信息,请参阅编辑。
      • 您的 Edit-2 的 uri 似乎有错字“api/Favorite/”...应该是“api/Favorites”吗?
      • @Kiran,实际上,我已将我的控制器从“FavoritesController”重命名为“FavoriteController”,这就是你看到的原因。还有其他线索吗?
      【解决方案3】:

      另一种方法是发布匿名类型,并让控制器接受动态。

      var response = client.PostAsJsonAsync(new { detailURI, pagingInfo }).Result;
      
      [HttpPost]
      public List<FavoriteDTO> GetFavoritesPaged([FromBody]dynamic model)
      {
          PagingInfo pagingInfo = (PagingInfo)model.pagingInfo;
          long userid = (long)model.userId;
      
          ...
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 1970-01-01
        • 1970-01-01
        • 2019-11-08
        • 2013-09-27
        • 2019-06-07
        • 2019-07-23
        相关资源
        最近更新 更多