2017-05-10 209 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");