Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple POST with HttpClient

I have two ASP.NET Core 2.1 apps and I'm trying to make a simple POST call from one app to the other using HttpClient.

For some reason, when I use [FromBody] to get the simple text I'm trying receive, I get a BadRequest error.

Here's my code on the sender. First, this is what's in my ConfigureServices method. I'm using the new HttpClientFactory feature in ASP.NET Core 2.1. I also created a client class named myApiCallerClient that handles my API calls:

services.AddHttpClient("myNamedClient", client =>
{
    client.BaseAddress = new Uri("http://localhost:50625/api/");
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

services.AddScoped(x => {
   var httpClientFactory = x.GetRequiredService<System.Net.Http.IHttpClientFactory>();
   var myApiCallerClient = httpClientFactory.CreateClient("myNamedClient");
   return new Clients.ApiCaller.ApiCallerClient(myApiCallerClient);
});

Here's the code in myApiCallerClient:

public async Task SayHello()
{
     var response = await _httpClient.PostAsync("test", new StringContent("Saying hello!", System.Text.Encoding.UTF8, "text/plain"));
}

And here's my code on the receiving end which is the POST() API method in TestController:

[HttpPost]
public async Task Post([FromBody]string input)
{
    // Some logic
}

My call doesn't hit this method if I use [FromBody] and I get BadRequest error on the sender. If I use [FromHeader] my request hits this API method but I'm getting a null value.

What am I doing wrong here?

like image 309
Sam Avatar asked Nov 30 '18 18:11

Sam


1 Answers

ASP.NET Core doesn't support a Content-Type of text/plain out of the box, so the server is rejecting your request as it's not something that it can parse when using the [FromBody] attribute.

In the comments, you said:

Ultimately I won't be sending text. My main concern here is that I'm not hitting my API method. [...] Once I make sure everything is working, I'll be sending JSON data which will get deserialized on the receiving end.

In order to test whether the problem is due to the text/plain Content-Type, you can update your PostAsync line to something like this:

var response = await _httpClient.PostAsync(
    "test",
    new StringContent("\"Saying hello!\"", System.Text.Encoding.UTF8, "application/json"));

As application/json is a supported Content-Type by default, the code above uses that and wraps the value you were sending with "s in order to make it a valid JSON value.

like image 67
Kirk Larkin Avatar answered Oct 04 '22 20:10

Kirk Larkin