0

I am trying to use the HttpClient class to call a POST method from my API which is supposed to add Server information to a DB.

The way I'm trying to call it is below. But when I step through it to debug it steps through my if statement for response.IsSuccessStatusCode.

public static async Task<Server> PostServer(Server server)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:50489/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            StringContent content = new StringContent(JsonConvert.SerializeObject(server));
            // HTTP POST
            HttpResponseMessage response = await client.PostAsync("api/Server/", content);
            if (response.IsSuccessStatusCode)
            {
                string data = await response.Content.ReadAsStringAsync();
                server = JsonConvert.DeserializeObject<Server>(data);
            }
        }
        return server;
    }

Also here is the POST method in my API below it was automatically generated in VS.

// POST: api/Servers
    [ResponseType(typeof(Server))]
    public async Task<IHttpActionResult> PostServer(Server server)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Servers.Add(server);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = server.Server_ID }, server);
    }
Zybrith
  • 1
  • 1
  • 1
  • 1
    What's the question? – Christos Nov 21 '17 at 16:57
  • 1
    Possible duplicate of [How to post data using HttpClient?](https://stackoverflow.com/questions/20005355/how-to-post-data-using-httpclient) – Mike Cheel Nov 21 '17 at 16:59
  • Use a tool like Fiddler to see what is actually being returned by your API. Sounds like it's returning an error. Without more information it's impossible to tell what's going on here. – Nate Barbettini Nov 21 '17 at 16:59
  • Try adding the `[HttpPost]` attribute to the action on your server. Without it you're probably getting a 404. – phuzi Nov 21 '17 at 17:02
  • It would be interesting to know what the status code is, it's usually quite clear what the problem is. How did you encode your data? Accept Header refers just one media. I see that is a localserver, but is it accepting that format? The size of the POST data is usually necessary too. – Jimi Nov 21 '17 at 20:07

0 Answers0