【问题标题】:Posting a string to asp.net core webapi through httpclient fails with a bad request通过 httpclient 将字符串发布到 asp.net core webapi 失败,请求错误
【发布时间】:2020-11-22 19:23:11
【问题描述】:

我在将字符串发布到 Web api 时收到来自 HttpClient 的错误请求错误。我知道如果我在 web api 中有一个对象作为参数,这将起作用,但我想要一个可以接受字符串并返回字符串的方法。这个 api 在 POSTMAN 中工作。这里是api和HttpClient的代码L

WebAPI 代码:

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

Http 客户端代码:

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;

在 Visual Studio 中调试期间,它在 var response = await httpClient.PostAsync(API_URL, stringContent) 的客户端代码中失败

我收到的错误:

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

【问题讨论】:

    标签: c# asp.net-core asp.net-web-api httpclient asp.net-core-3.1


    【解决方案1】:

    由于您使用简单的字符串来接收数据,因此无需将其设置为对象。

    只需序列化字符串。

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

    结果:

    【讨论】:

      【解决方案2】:

      因为在邮递员中,即使您将 JSON 设置为类型,您传递的也是纯文本(字符串)类型。您的控制器适合仅接收字符串,因此它可以在邮递员中使用。

      有效的json:

      {
        "ActivationCode":"FFFF",
        "Email": "joe@email.com"
      }
      

      您可以直接在postAsync 中传递jsonString 以使其从后面的代码中工作。

      【讨论】:

        猜你喜欢
        • 2021-03-24
        • 1970-01-01
        • 2019-02-25
        • 2017-10-29
        • 1970-01-01
        • 2018-10-08
        • 2020-11-15
        • 1970-01-01
        • 2020-04-21
        相关资源
        最近更新 更多