带有异步和等待的HTTPClient PostAsync()永远不会返回消息

时间:2017-05-10 06:05:35

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

我的问题是当我尝试使用HttpClient PostAsync()从mvc应用程序调用我的Web API rest Service时,我的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;
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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