Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API?

Viewed 5932

On client side, I Post a request using HttpClient class to an ASP.net core web API on server side.

I want to send a string ("OK") in the body of the request, and a string argument (numStr=5) in the header, I've read many similar thread but still failed.

Here is the Client Method:

public async void SendBodyAsync(Action<string> onRespond)
{
    try
    {
        string URL = "http://localhost:60039/api/calculator/AddMore";

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);
        request.Headers.Add("numStr", "5");

        request.Content = new StringContent("OK", Encoding.UTF8, "text/plain");   //causes error

        HttpResponseMessage response = await mHttpClient.SendAsync(request);
        response.EnsureSuccessStatusCode();

        string result = await response.Content.ReadAsStringAsync();
        onRespond(result);
    }
    catch (HttpRequestException ex)
    {
        Debug.LogError(ex);       //Unity3D console Debug
        onRespond(null);
    }
}

Here is the Server Action:

[Route("api/[controller]/[action]")]
[ApiController]
public class CalculatorController : ControllerBase
{
    public string AddMore([FromHeader]string numStr)
    {
        //string bodyStr;
        //get string from Request.Body and set the value to bodyStr
        return (int.Parse(numStr) + 10).ToString();
    }
}

If I remove the line request.Content = new StringContent("OK", Encoding.UTF8, "text/plain"); from the client method, the respond value is 15 which is correct.

But with the request.Content, the client shows the error:

An error occurred while sending the request ---> System.Net.WebException: The request requires buffering data to succeed.

The server break point is not triggered, so the request was not sent out successfully.

I have created another very simple server method using HttpListener, it reads the request.Content as clientContext stream correctly. I think maybe the problem is that request.Content is not equal to Http body, and it's unlikely a buffering issue as the error message says.

My questions are,

  1. How to send a string in Http body correctly, it's not argument and can be long (like a complete player profile in string format), so it's not proper for header or query or...
  2. How can I receive and parse the string in the request body on server side correctly?

Thank you so much for reading my post.

2 Answers

Looking at your AddMore method. I think you should also get the body content using the [FromBody] string parameter as well, I do not see it specified.

Note also if you do not specify accept/content type it is by default application/json in .NET core

P.S Also consider making your AddMore method an async method

I don't know why I can't editor my own thread. Just want to say I re-created a project and pasted the same code, and it worked. Maybe people who see the error message "An error occurred while sending the request ---> System.Net.WebException: The request requires buffering data to succeed" can try the same. Hope it helps.

Related