首页 > 解决方案 > 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;

一切正常。

有什么问题???

标签: asp.net-core

解决方案


好的,我修好了...

可以想象,问题在于调用 postasync 的函数是异步的,但之前的函数不是,而且我没有为那个函数创建 .Wait()。

与asp net core无关,只是同步代码中的异步代码问题。


推荐阅读