c# - 如何从服务器端获取字符串内容?
问题描述
我有一个客户这样调用我的 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();
解决方案
首先,对于 API 方法,您通常会返回一个HttpResponseMessage
您可以使用Request.CreateResponse(HttpStatusCode, Message)
.
现在对于您的问题,在 Asp.Net 中,API 方法具有根据您期望发送的参数。例如,在您的情况下,您的 Method signatrue 看起来像这样public HttpResponseMessage GetStringContent([FromBody] Dictionary<string, string> stringContent)
。Post 方法中使用[FromBody]
Attribute 来表示 Content 来自请求正文
推荐阅读
- java - 不好的做法或不赞成使用逗号分隔大小写?切换 case 语句 Java
- reactjs - React - 方法不更新 DOM
- typescript - 为什么打字稿将未知范围缩小到永远不会在可到达的条件块内?
- sql - 将 OVER (PARTITION BY ...) 与 GROUPING SETS 结合起来?
- scala - sacla 中的 private[wikipedia] 是什么意思?
- javascript - Res.send 和如果功能混淆..?
- python-3.x - 队列 O(1) 没有在 python 中快速追加或弹出
- python - Discord.py 检查会员状态
- sql - 如何用用例构造条件更新
- python - 使用pandas读取excel时如何确保数字读取为字符串?