I have a Web API action as following:
[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;
}
I need to call it using HttpClient and I am trying it as following:
paging info needs to be passed to the get method.
var pagingInfo = new PagingInfo()
{
PageIndex = 1,
PageSize = 10,
OrderBy = "URL",
OrderDirection = OrderDirection.Desc
};
where OrderDirection is an enum:
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));
But, its not working. It says internal server error, what I am missing here; is the enum causing problem or something else? I have other WebAPIs working just fine; none of them has more than one parameter like this.
Here is my routConfig:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Is it the right way to call the WebAPI with multiple parameters or is there a better way, please suggest?
EDIT-1: changed this:
var detailURI = "Favorites/GetFavoritesPaged?userId?"+34;
to:
var detailURI = "Favorites/GetFavoritesPaged?userId="+34;
All it was a typo :)
EDIT-2:
With EDIT-1 the request goes to follwing WebAPI method (which is wrong):
[HttpPost]
public FavoriteDTO AddToFavorites(FavoriteDTO favoriteDTO)
{
------code to add to db------
}
But, when I edited the routeConfig to the following:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Then I started getting the following exception:
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}}