Posting a string to asp.net core webapi through httpclient fails with a bad request [closed]

I am getting Bad Request error from HttpClient while posting a string to a web api. I know this will work if I have a object as paraneter in web api, but I want to have a method that can accept a string and return a string. This api works in POSTMAN. Here is the api and HttpClient codeL

WebAPI Code:

[HttpPost("TestMethod")]
        public ActionResult<string> TestMethod([FromBody] string testString)
        {
            var s = "Hello: " + testString;
            return Content(s.ToString());
        }

Http Client Code:

string apiResponse="";

            string API_URL = configuration["AaushadhaAPI_URL"].ToString() + "mauser/TestMethod";
            var postParameters = new { testString = "Bob" };
            var jsonString = JsonConvert.SerializeObject(postParameters);
            var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.PostAsync(API_URL, stringContent))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        apiResponse = await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        //Handle error
                    }
                }
            }
            return apiResponse;

During debugging in Visual Studio, it fails in client code apiResponse = await response.Content.ReadAsStringAsync();

Error I received:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Transfer-Encoding: chunked
  Server: Kestrel
  X-Powered-By: ASP.NET
  Date: Mon, 23 Nov 2020 01:36:44 GMT
  Content-Type: application/problem+json; charset=utf-8
}}


Read more here: https://stackoverflow.com/questions/64958513/posting-a-string-to-asp-net-core-webapi-through-httpclient-fails-with-a-bad-requ

Content Attribution

This content was originally published by WinFXGuy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: