【问题标题】:HttpResponseMessage Content is always an empty stringHttpResponseMessage 内容始终为空字符串
【发布时间】:2022-02-05 03:53:35
【问题描述】:

我的 MVC API 客户端应用程序的基类中有一个通用的 post 方法:

    protected async Task<T> PerformPostAsync<T>(string requestUri, HttpContent c)
    {
        _webApiClient = new HttpClient { BaseAddress = _baseAddress };
        _webApiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
        var webApiResponse = await _webApiClient.PostAsync(requestUri, c);
        var responseContent = webApiResponse.Content.ReadAsStringAsync().Result;
        return JsonConvert.DeserializeObject<T>(responseContent);
    }

我正在调用上面的方法来发布一个对象:

    public async Task<HttpResponseMessage> AddEmployee(EmployeeImport employee)
    {
        var param = Newtonsoft.Json.JsonConvert.SerializeObject(employee);
        HttpContent contentPost = new StringContent(param, System.Text.Encoding.UTF8, "application/json");
        var response = await PerformPostAsync<HttpResponseMessage>("entity/NewEmployee", contentPost);
        return response;
    }

在我的Web API方法中,public async Task &lt;IActionResult&gt; CreateEmployee([FromBody]EmployeeImport Employee),如果成功,我有return Ok();

在 PerformPostAysnc 方法中,如果我将鼠标悬停在 var webApiResponse 上,它会显示为 Status: OK 但当我调用此行时:

var responseContent = webApiResponse.Content.ReadAsStringAsync().Result;

responseContent 始终为空字符串,因此我的 AddEmployee 方法中的响应始终为空:

var response = await PerformPostAsync<HttpResponseMessage>("entity/NewEmployee", contentPost);

另外,如果我强制它抛出错误,它会显示错误:

然后,当它到达发起 Post 的调用时,响应显示状态码 OK:

我无法弄清楚我做错了什么。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    我能够通过将我的 API 方法从返回 &lt;IActionResult&gt; 更改为返回 &lt;HttpResponseMessage&gt; 来获得 OK 响应,因此我现在确实收到了成功消息。

     public async Task <HttpResponseMessage> CreateEmployee([FromBody]EmployeeImport Employee)
    
            if(success)
            {
                return new HttpResponseMessage(HttpStatusCode.OK);
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 2014-08-18
      • 1970-01-01
      • 2012-06-15
      • 2020-12-19
      相关资源
      最近更新 更多