首页 > 解决方案 > 来自 PostAsync 的内部服务器错误

问题描述

我有下面的方法将数据发布到 URL

    public async Task<IActionResult> PostAsync(string method, string data, bool isJson = true, long key = 0)
    {
        IActionResult result;
        try
        {
            var proxyUrl = await EstablishProxyUrlAsync(method, key).ConfigureAwait(false);
            var content = isJson ? new StringContent(data, Encoding.UTF8, "application/json") : new StringContent(data);

            var response = await this._httpClient.PostAsync(proxyUrl, content).ConfigureAwait(false);
            result = await ProcessResponseAsync(response).ConfigureAwait(false);
        }
        catch (Exception e)
        {
            Log.Error(e, this.GetType().Name + ": Error in PostAsync");
            throw;
        }

        return result;
    }

如您所见,我正在设置 ContentType,大量关于处理 StringContent 的帖子都说使用此方法。

但是,我只是把这个拿回来

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Sun, 29 Jul 2018 19:19:35 GMT
  Server: Kestrel
  Content-Length: 0
}}

就查看问题所在而言,这显然是一个非常无用的响应

被调用的方法如下

[HttpPost]
[ActionName("Add")]
public async Task<IActionResult> AddAsync(StringContent content)
{
    var myJson= await content.ReadAsStringAsync().ConfigureAwait(false);
    var object= JsonConvert.DeserializeObject<MyObject>(myJson);
    var result = await _service.AddAsync(object).ConfigureAwait(false);

    return result;
}

如您所见,我已经包含了 HttpPost

有谁知道这可能是什么原因?

我正在使用服务结构,并且此 URL 位于分区上,但我认为这不是问题,因为此路由适用于其他区域

保罗

标签: c#asp.net-mvcasp.net-web-apiasp.net-core

解决方案


被调用的方法应该被重构以遵循正确的语法并将模型传递给动作,并让模型绑定器用传入的数据填充它。

[HttpPost]
[ActionName("Add")]
public async Task<IActionResult> AddAsync([FromBody] MyObject model) {
    var result = await _service.AddAsync(model);
    return result;
}

假设在等待时_service.AddAsync(model);返回IActionResult

ASP.NET Core 中的参考模型绑定


推荐阅读