【问题标题】:HTTPClient PostAsync() with async and await never returns message带有异步和等待的 HTTPClient PostAsync() 从不返回消息
【发布时间】:2017-05-10 06:05:34
【问题描述】:

我的问题是当我尝试使用 HttpClient PostAsync() 从 mvc 应用程序调用我的 Web API REST 服务时,我的 Web API 永远不会返回响应消息。

这里是 mvc 应用代码:

public async Task<string> sendToWebAPI(string _obj)
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebAPIRestService"]);
            StringContent _jsonParameter = new StringContent(_obj, Encoding.UTF8, "application/json");

            HttpResponseMessage Res = await client.PostAsync("api/webAPIController/", _obj).ConfigureAwait(false);               
            var WebAPIResponse = await Res.Content.ReadAsStringAsync();

            return WebAPIResponse;

        }
    }

MVC Web API 代码:

    [HttpPost]
    public async Task<string> Dowork([FromBody] string _obj)
    {
      HttpResponseMessage result = Request.CreateResponse(_obj != "" ? HttpStatusCode.OK : HttpStatusCode.InternalServerError);
      return result;
    }

谢谢!

【问题讨论】:

  • 请使用 camelCase 命名变量,使用 PascalCase 命名方法。

标签: c# asp.net asp.net-mvc asynchronous asp.net-web-api


【解决方案1】:

您的 API 代码当前未返回字符串。它正在返回 OK 或 InternalServerError。修改你的代码如下。

bool isOK = string.isNullOrEmpty(_obj);
result = isOK ? request.CreateResponse<string>(HttpStatusCode.OK, _obj) :
request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Invalid Data");

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2019-10-10
    • 2013-04-12
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多