如何从服务器端获取stringContent?

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

我有一个客户端调用我的API服务,如下所示:

var paramDiction = new Dictionary<string, string>{{"datefROM", "2018/1/1"}};
string content = JsonConvert.SerializeObject(paramDiction);
var stringContent = new StringContent(content, Encoding.UTF8, "application/json");
// call the API service
var x = await _httpClient.PostAsync(url, stringContent);

我尝试了很多方法从服务器端获取stringContent,但仍然无法获得它。我是在走错路吗?

    [HttpPost]
    [Route("GetStringContent")]
    public IActionResult GetStringContent()
    {
        var stringContent = Request.HttpContext.ToString();

        return stringContent;
    }

不知道为什么这里的Request是一个httpRequest,只有HTTPContext并且这个httpContent无法读出内容就好了

    Request.Content.ReadAsStringAsync();
c# asp.net asp.net-core
1个回答
1
投票

首先,对于API方法,您通常会返回一个可以使用HttpResponseMessage创建的Request.CreateResponse(HttpStatusCode, Message)

现在问题,在Asp.Net中,API方法根据您期望发送的内容提供参数。例如,在您的情况下,您的Method signatrue看起来像这个public HttpResponseMessage GetStringContent([FromBody] Dictionary<string, string> stringContent)。在后方法中使用[FromBody]属性来表示内容来自请求正文

© www.soinside.com 2019 - 2024. All rights reserved.