从挂起的MVC控制器调用Web API

时间:2018-10-22 03:30:45

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

在过去的几个小时中,我尝试了许多不同的方法,但是我的方法调用却挂了线程。

这是我的Web API代码,当从MVC客户端进行AJAX调用时,它可以很好地工作,但是我正在尝试测试从服务器进行的调用:

// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

下面是我的MVC控制器代码和型号代码:

public async Task<ActionResult> TestApi()
{
    try
    {
        var result = await VoipModels.GetValues();

        return MVCUtils.JsonContent(result);
    }
    catch (Exception ex)
    {
        return MVCUtils.HandleError(ex);
    }
}
...
    public static async Task<string[]> GetValues()
    {
        string[] result = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:44305/api/");

            //THIS IS THE LINE THAT HANGS UP - I'VE TRIED MANY VARIATIONS
            var response = await client.GetAsync("values", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsAsync<string[]>();
            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }

        return result;
    }

我在调用单独的第三方API时成功使用了这种格式。我用了几个小时的Google搜寻功能,没有足够的示例可以尝试。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

  1. 检查您的端口号。根据您的代码,您已经对端口"http://localhost:44305/api/"进行了“硬编码”,这可能是不正确的,您应该将其转换为从主机获取 配置。
  2. 检查您本地计算机的防火墙。请确保您本地计算机的防火墙允许连接到分配的端口。
  3. 检查您的协议。确保在请求URL中正确使用http或https。

作为一个特别说明,您可能希望自己进行Web API服务器调用的情况非常罕见/异常。这样做是一种效率很低的设计,因为它会浪费资源而得不到任何收益(例如生成请求和响应)。