使用C#HttpClient,如何将字符串HttpContent发布到ASP.net Core Web API?

问题描述 投票:0回答:1

在客户端,我使用HttpClient类将请求发布到服务器端的ASP.net核心Web API。

我想在请求的正文中发送一个字符串(“ OK”),并在标题中发送一个字符串参数(numStr = 5),我已经阅读了很多类似的线程,但是仍然失败。

这里是客户端方法:

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

这是服务器操作:

[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();
    }
}

如果我删除“ request.Content = new StringContent(“ OK”,Encoding.UTF8,“ text / plain”);通过客户端方法,响应值为“ 15”,这是正确的。

但是对于request.Content,客户端显示错误“发送请求时发生错误---> System.Net.WebException:请求需要缓冲数据才能成功”。服务器断点未触发,因此未成功发送请求。

我使用HttpListener创建了另一个非常简单的服务器方法,它正确读取了request.Content作为clientContext流。我认为问题可能出在request.Content不等于Http主体,并且不太可能像错误消息中所述的那样出现缓冲问题。

我的问题是,1.如何正确地在Http正文中发送字符串,它不是参数,并且可能很长(就像完整的字符串格式的播放器配置文件),因此不适用于标头或查询或...2.如何正确接收并解析服务器端请求正文中的字符串?

非常感谢您阅读我的文章。

c# asp.net-web-api dotnet-httpclient
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.