locked
HttpClient doesn't see my MVC application RRS feed

  • Question

  • User2018604576 posted

    Hello, i have a web api controller which have an action:

    // GET api/values
            public IEnumerable<string[]> Get()
            {
                List<string[]> list = new List<string[]>();
                list.Add(new string[] { "1", "Bellarus", "Minsk" });
                list.Add(new string[] { "2", "Russia", "Moscow" });
                list.Add(new string[] { "3", "France", "Pariz" });
                list.Add(new string[] { "4", "England", "London" });
                list.Add(new string[] { "5", "Afghanistan", "Kabul" });
     
                return list;
            }

    I need to get a json file from this action. I make so: 

    class Program
        {
            static void Main(string[] args)
            {
                GetRequest();
            }
    
            async static void GetRequest()
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                    HttpResponseMessage response = await client.GetAsync("http://localhost:52796/api/values");
                    if (response.IsSuccessStatusCode)
                    {
                        string s = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(s);
                    }
                    else
                    {
                        Console.WriteLine("Internal server Error");
                    }
                }
            }
        }

    But, it doesn't work, response.IsSuccessStatusCode returns false. But if i change a request to http://google.com It works.

    Also, it doesn't work with another actions (not only with web api, with normal cotrollers too).

     

    Saturday, January 27, 2018 11:03 PM

Answers

  • User2018604576 posted

    I found out an issue. I used a windows authentication. As i understood HttcpClient doens't connect to my app when i use windows authentication. Then i just used WebClient instead HttpClient and it has done.

    static void Main(string[] args)
            {
                using (var client = new WebClient { UseDefaultCredentials = true })
                {
                    client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
                    string s = client.DownloadString("http://localhost:52796/api/values");
                    Console.WriteLine(s);
                }
                Console.ReadKey();
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 28, 2018 12:31 PM