0

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["API_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 at var response = await httpClient.PostAsync(API_URL, stringContent)

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
}}
0

2 Answers 2

3

Since you use a simple string to receive the data, there is no need to set it as an object.

Just Serialize the string.

var postParameters = "Bob";
var jsonString = JsonConvert.SerializeObject(postParameters);
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Because in postman, even though you set JSON as type, you are passing plaintext(string) type. Your controller is suitable to receive only string so it works in postman.

Valid json:

{
  "ActivationCode":"FFFF",
  "Email": "[email protected]"
}

You can directly pass the jsonString in postAsync to make it work from code behind.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.