简体   繁体   中英

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

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

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:

在此处输入图片说明

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": "joe@email.com"
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM