Reputation: 2494
I'm learning web api, well trying to - I've hit a snag. I can post to it fine and get a response when there are no parameters in the method on the api, e.g this works...
client
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + T.Access_Token);
var req = new HttpRequestMessage(HttpMethod.Post, "https://baseurl/api/controller/sites");
var response = await client.SendAsync(req);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
List<Site_2016> sites = Library.Data.Json.FromJson<List<Site_2016>>(result);
return sites;
}
else return new List<Site_2016>();
}
Api
[HttpPost]
[Route("sites")]
public async Task<IHttpActionResult> GetSites()
{
//Do stuff
return Ok(Sites);
}
But I can't for the life of me get it to work when I pass through some parameters like so...
client
using (var client = new HttpClient())
{
Dictionary<String, String> dict = new Dictionary<string, string>();
dict.Add("identifier", instance);
dict.Add("endOfDay", IsEndOfDayOnly.ToString());
var content = new FormUrlEncodedContent(dict);
client.BaseAddress = new Uri("https://baseurl/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + T.Access_Token);
var response = await client.PostAsync("api/controller/lastsaledate", content);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
KeyValuePair<String, DateTime> LastPush = Library.Data.Json.FromJson<KeyValuePair<String, DateTime>>(result);
return LastPush;
}
else
{
return new KeyValuePair<string, DateTime>();
}
}
Api
[HttpPost]
[Route("lastsaledate")]
public async Task<IHttpActionResult> GetLastSalesUpdate(string identifier, bool endOfDay)
{
//do stuff
return Ok(Result);
}
The response returns 404, I was wandering if it could be a routing issue perhaps? The bearer token is valid for both posts, if I disable authorization then I get the same result. The api/controller/action url is definitely correct.
Upvotes: 1
Views: 3145
Reputation: 3169
Yes, in this case in particular you can try this
var response = await client.PostAsync(string.format("api/controller/lastsaledate?identifier={0}&endOfDay{1}",instance,IsEndOfDayOnly), content);
And remove the dict
Or you can try this
[HttpPost]
[Route("lastsaledate")]
public async Task<IHttpActionResult> GetLastSalesUpdate([FromBody]string identifier, [FromBody]bool endOfDay)
{
//do stuff
return Ok(Result);
}
Or you can try this
[HttpPost]
[Route("lastsaledate")]
public async Task<IHttpActionResult> GetLastSalesUpdate(testClass myParam)
{
//do stuff
return Ok(Result);
}
public class testClass
{
public string identifier;
public bool endOfDay;
}
Upvotes: 1