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.

4
  • 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 Commented Mar 13, 2018 at 20:10
  • 1
    Possible duplicate of Angular2 HTTP Post ASP.NET MVC Web API Commented Mar 13, 2018 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. Commented Mar 13, 2018 at 20:13
  • btw: You could get around this issue by passing in query string parameters and marking the parameters with the FromUrl attribute. Commented Mar 13, 2018 at 20:20

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

[FromBody] can only be used once. Reference Parameter Binding in ASP.NET Web API. Re check your answer you are almost there with the correct solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.