asp.net-core - ASP NET Core 中 PostAsync 异常的自定义 InputFormatter
问题描述
我有一个奇怪的问题,我不知道为什么会出现问题:
在客户端,我有这个代码:
HttpResponseMessage response = await _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test"));
在服务器上,我实现了一个自定义 InputFormatter 有这个
public async override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
try
{
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync().ConfigureAwait(false);
return await InputFormatterResult.SuccessAsync(content).ConfigureAwait(false);
}
}
catch (Exception e)
{
return await InputFormatterResult.FailureAsync();
}
}
如果我尝试这个,服务器的 catch 异常会被触发,给我一个异常:
现有连接被远程主机强行关闭
但.....
如果在客户端我使 PostAsync “同步”这样做:
HttpResponseMessage response = _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test")).Result;
一切正常。
有什么问题???
解决方案
好的,我修好了...
可以想象,问题在于调用 postasync 的函数是异步的,但之前的函数不是,而且我没有为那个函数创建 .Wait()。
与asp net core无关,只是同步代码中的异步代码问题。
推荐阅读
- php - 我的函数花费的时间太长并导致页面超时
- mips - 将 qemu 图像移动到真实设备
- django - 从 Django 频道组中删除特定用户?
- python - MySQL 连接器无法处理参数
- r - 使用循环从多个文件中提取特定行
- css - 如何更改html组合框中图标的位置?
- django - NoReverseMatch 在 django 中有 2 个 slug 参数
- java - 如何在 Android Studio 中从 Java 代码执行 Python 代码?
- search - Flutter - 更改 SearchDelegate 的搜索提示文本
- group-by - groupby 并在 pyspark 中加入 vs 窗口