WebApi controller has to post model to a separate Api. Is this possible and if so, how?
Asked
Active
Viewed 1,876 times
0
-
Possible duplicate of [Generate http post request from controller](http://stackoverflow.com/questions/1705442/generate-http-post-request-from-controller) – CodeCaster Jan 05 '16 at 09:55
-
1There's nothing special about being in a controller. You can just issue an HTTP request like you would from any C# code. – CodeCaster Jan 05 '16 at 09:55
-
@CodeCaster First of all, not everyone know that one can just make an HTTP request from any C# code. Atleast I didn't! People facing same problem may come to this question to clarify doubt. Moreover, the answer here is quiet different from the post you linked. You could have wrote an answer explaining your view. – Shyamal Parikh Jan 05 '16 at 10:32
-
No, I won't post an answer, because I don't like duplicating content. There are three ways in the BCL to perform HTTP requests (`HttpWebRequest`, `WebClient`, `HttpClient`), the duplicate mentions the first. You could've found that you can make HTTP calls from C# by searching. :) See for example [HTTP request with post](http://stackoverflow.com/questions/4015324/http-request-with-post). – CodeCaster Jan 05 '16 at 10:37
1 Answers
3
Yes, this is possible using the HttpClient
class.
Here's an example:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://example.com");
var content = new StringContent("{\"foo\":\"bar\"}", Encoding.UTF8, "application/json");
await client.PostAsync("/api", content);
}
And if you already have a model you could JSON serialize it before passing:
string json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
There's also the PostAsJsonAsync
extension method which could be used to simplify the code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://example.com");
await client.PostAsJsonAsync("/api", model);
}

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
1The `PostAsync` method returns a `Task
`. So once you have awaited on it and got the corresponding `HttpResponseMessage`, all you have to do is look at the `StatusCode` property. Just like that: `var result = await client.PostAsync("/api", content);` and just use `result.StatusCode`. There's also a convenient `result.IsSuccessStatusCode` boolean property that you might check. – Darin Dimitrov Jan 05 '16 at 10:00