2017-05-10 208 views
1

我的问题是,当我尝试从使用HttpClient PostAsync()的mvc应用程序调用我的Web API rest服务时,我的web api从不返回响应消息。HTTPClient PostAsync()与异步并等待永不返回消息

这里是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; 
    } 

谢谢!

+0

请使用camelCase命名变量和命名您的方法的PascalCase。 –

回答

0

您的API代码当前没有返回字符串。它回到OK或InternalServerError。如下修改您的代码。

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