简体   繁体   中英

Call Web API from MVC Controller Hanging Up

I've tried many different approaches for the past couple of hours, but my method call is hanging up the thread.

Here is my Web API code, which works fine when making AJAX call from the MVC client, but I'm trying to test calling from the server:

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

Below is my MVC controller code and model code:

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;
    }

I've used this format successfully when calling a separate, 3rd party API. I've run out of examples to try from my couple of hours of Googling.

What am I doing wrong here?

  1. Check your port number. Based on your code, you have "hard coded" the port "http://localhost:44305/api/" which may likely be incorrect, you should convert that to grab it from the host configuration instead.
  2. Check your local machine's firewall. Make sure that your local machine's firewall is allowing connections to the port assigned.
  3. Check your protocol. Ensure that you are using http or https appropriately in your request URL.

As a special note, there are very rare cases / exception cases that you would want to have a web API server call itself. Doing so, is rather inefficient design as it will consume resources for no gain (such a generating request and response).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM