首页 > 解决方案 > 如何从服务器端获取字符串内容?

问题描述

我有一个客户这样调用我的 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.netasp.net-core

解决方案


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

现在对于您的问题,在 Asp.Net 中,API 方法具有根据您期望发送的参数。例如,在您的情况下,您的 Method signatrue 看起来像这样public HttpResponseMessage GetStringContent([FromBody] Dictionary<string, string> stringContent)。Post 方法中使用[FromBody]Attribute 来表示 Content 来自请求正文


推荐阅读