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,
- 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...
- How can I receive and parse the string in the request body on server side correctly?
Thank you so much for reading my post.