【问题标题】:Web ApI: HttpClient is not invoking my web api actionWeb ApI:HttpClient 没有调用我的 Web api 操作
【发布时间】:2018-05-26 00:57:53
【问题描述】:

首先看看我是如何设计我的 web api 动作的。

[System.Web.Http.RoutePrefix("api/Appointments")]
public class AppointmentsServiceController : ApiController
{

    [System.Web.Http.HttpGet, System.Web.Http.Route("UserAppointments/{email}")]
    public IHttpActionResult UserAppointments(string email)
    {
        if (!string.IsNullOrEmpty(email))
        {
            AppointmentsService _appservice = new AppointmentsService();
            IEnumerable<Entities.Appointments> app = _appservice.GetUserWiseAppointments(email);

            if (app.Count() <= 0)
            {
                return NotFound();
            }
            else
            {
                return Ok(app);
            }
        }
        else
        {
            return BadRequest();

        }

    }
}

现在我通过 HttpClient 从我的 asp.net mvc 操作中调用 web api 操作。

    public async Task<ActionResult> List()
    {

        var fullAddress = ConfigurationManager.AppSettings["baseAddress"] + "api/Appointments/UserAppointments/" + Session["useremail"];

        IEnumerable<Entities.Appointments> app = null;
        try
        {
            using (var client = new HttpClient())
            {
                using (var response = client.GetAsync(fullAddress).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var customerJsonString = await  response.Content.ReadAsStringAsync();
                        app = JsonConvert.DeserializeObject<IEnumerable<Entities.Appointments>>(customerJsonString);
                    }
                    else
                    {
                        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                        var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
                        //MessageBox.Show(dict["Message"]);
                    }
                }
            }
        }
        catch (HttpRequestException ex)
        {
            // catch any exception here
        }

        return View();
    }
 }

我想捕获返回的 IEnumerable,如果不是数据返回,我也必须捕获。请告诉我正确的方向。

我在哪里犯了错误。谢谢

【问题讨论】:

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


    【解决方案1】:

    将异步与阻塞调用(如.Result)混合使用

    var response = client.GetAsync(fullAddress).Result
    

    response.Content.ReadAsStringAsync().Result
    

    可能导致死锁,这可能是它无法访问您的 API 的原因。

    将代码重构为始终异步。

    这意味着将using 更新为

    var response = await client.GetAsync(fullAddress)
    

    并将else语句中的内容读取到

    await response.Content.ReadAsStringAsync()
    

    参考Async/Await - Best Practices in Asynchronous Programming

    【讨论】:

      【解决方案2】:

      您似乎没有在等待您的 GetAsync 调用,因此在下面的 if (response.IsSuccessStatusCode) 可能总是返回 false。尝试像这样调用你的方法:

      using (var response = (await client.GetAsync(fullAddress)).Result)
      {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-10
        • 2014-10-14
        • 1970-01-01
        • 2020-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多