locked
How to POST a string HttpContent using HttpClient to an ASP.net Core web API? RRS feed

  • Question

  • User-1758582694 posted
    Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API?
     
    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 an 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.
    Wednesday, February 26, 2020 7:21 PM

Answers

  • User1120430333 posted

    <div>Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API?</div> <div> </div> <div>On client side, I Post a request using HttpClient class to an ASP.net core web API on server side.</div> <div> </div> <div>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.</div> <div> </div> <div>Here is the Client Method:</div> <div> </div> <div>    public async void SendBodyAsync(Action<string> onRespond)</div> <div>    {</div> <div>        try</div> <div>        {</div> <div>            string URL = "http://localhost:60039/api/calculator/AddMore";</div> <div> </div> <div>            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);</div> <div>            request.Headers.Add("numStr", "5");</div> <div> </div> <div>            request.Content = new StringContent("OK", Encoding.UTF8, "text/plain");   //causes error</div> <div> </div> <div>            HttpResponseMessage response = await mHttpClient.SendAsync(request);</div> <div>            response.EnsureSuccessStatusCode();</div> <div> </div> <div>            string result = await response.Content.ReadAsStringAsync();</div> <div>            onRespond(result);</div> <div>        }</div> <div>        catch (HttpRequestException ex)</div> <div>        {</div> <div>            Debug.LogError(ex);       //Unity3D console Debug</div> <div>            onRespond(null);</div> <div>        }</div> <div>    }</div> <div>Here is the Server Action:</div> <div> </div> <div>[Route("api/[controller]/[action]")]</div> <div>[ApiController]</div> <div>public class CalculatorController : ControllerBase</div> <div>{</div> <div>    public string AddMore([FromHeader]string numStr)</div> <div>    {</div> <div>        //string bodyStr;</div> <div>        //get string from Request.Body and set the value to bodyStr</div> <div>        return (int.Parse(numStr) + 10).ToString();</div> <div>    }</div> <div>}</div> <div>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.</div> <div> </div> <div>But with the request.Content, the client shows an 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.</div> <div> </div> <div>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.</div> <div> </div> <div>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?</div> <div> </div> <div>Thank you so much for reading my post.</div>

    Your post is jacked-up and is not readable.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 26, 2020 10:38 PM

All replies

  • User1120430333 posted

    <div>Using C# HttpClient, how to POST a string HttpContent to ASP.net Core web API?</div> <div> </div> <div>On client side, I Post a request using HttpClient class to an ASP.net core web API on server side.</div> <div> </div> <div>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.</div> <div> </div> <div>Here is the Client Method:</div> <div> </div> <div>    public async void SendBodyAsync(Action<string> onRespond)</div> <div>    {</div> <div>        try</div> <div>        {</div> <div>            string URL = "http://localhost:60039/api/calculator/AddMore";</div> <div> </div> <div>            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);</div> <div>            request.Headers.Add("numStr", "5");</div> <div> </div> <div>            request.Content = new StringContent("OK", Encoding.UTF8, "text/plain");   //causes error</div> <div> </div> <div>            HttpResponseMessage response = await mHttpClient.SendAsync(request);</div> <div>            response.EnsureSuccessStatusCode();</div> <div> </div> <div>            string result = await response.Content.ReadAsStringAsync();</div> <div>            onRespond(result);</div> <div>        }</div> <div>        catch (HttpRequestException ex)</div> <div>        {</div> <div>            Debug.LogError(ex);       //Unity3D console Debug</div> <div>            onRespond(null);</div> <div>        }</div> <div>    }</div> <div>Here is the Server Action:</div> <div> </div> <div>[Route("api/[controller]/[action]")]</div> <div>[ApiController]</div> <div>public class CalculatorController : ControllerBase</div> <div>{</div> <div>    public string AddMore([FromHeader]string numStr)</div> <div>    {</div> <div>        //string bodyStr;</div> <div>        //get string from Request.Body and set the value to bodyStr</div> <div>        return (int.Parse(numStr) + 10).ToString();</div> <div>    }</div> <div>}</div> <div>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.</div> <div> </div> <div>But with the request.Content, the client shows an 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.</div> <div> </div> <div>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.</div> <div> </div> <div>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?</div> <div> </div> <div>Thank you so much for reading my post.</div>

    Your post is jacked-up and is not readable.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 26, 2020 10:38 PM
  • User-1758582694 posted

    I edited it several times, but the format is still a mess, but anyway, I re-created the project and the same method just worked .... I don't know why, but anyway, thanks for reading my thread.

    The method is as below, people may try re-creating the project if you encounter the error message "An error occurred while sending the request ---> System.Net.WebException: The request requires buffering data to succeed". Hope it helps.

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CalController : ControllerBase
    {
    public async Task<string> AddMore([FromHeader]string numStr)
    {
    string bodyMsg;
    using (StreamReader stream = new StreamReader(Request.Body))
    {
    bodyMsg = await stream.ReadToEndAsync();
    }
    return (int.Parse(numStr) + 10).ToString() + " " + bodyMsg;
    }
    }

    Thursday, February 27, 2020 10:32 AM
  • User1120430333 posted

    I edited it several times, but the format is still a mess, but anyway, I re-created the project and the same method just worked .... I don't know why, but anyway, thanks for reading my thread.

    The browser you are using has some kind of plugin software that's doing it. I suggest you use another browser to make post in the future,

    Thursday, February 27, 2020 1:12 PM