1

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.

Sean T
  • 2,414
  • 2
  • 17
  • 23
  • In App_Start/RouteConfig.cs, make sure you have the line routes.MapMvcAttributeRoutes(); Also, in your call to "lastsaledate", what is the value of your "content" variable – Lucas Mar 13 '18 at 20:10
  • 1
    Possible duplicate of [Angular2 HTTP Post ASP.NET MVC Web API](https://stackoverflow.com/q/36288523/1260204) – Igor Mar 13 '18 at 20:12
  • 1
    See the proposed duplicate. Although the question is about how to post multiple parameters the underlying problem is the same, with web api you can post 1 object so you need to consolidate your parameters into a single custom type and post that. – Igor Mar 13 '18 at 20:13
  • btw: You could get around this issue by passing in query string parameters and marking the parameters with the `FromUrl` attribute. – Igor Mar 13 '18 at 20:20

1 Answers1

1

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;
}
Victor Hugo Terceros
  • 2,969
  • 3
  • 18
  • 31
  • 1
    `[FromBody]` can only be used once. Reference [Parameter Binding in ASP.NET Web API](https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api). Re check your answer you are almost there with the correct solution. – Nkosi Mar 14 '18 at 00:23