C# HttpClient - localhost works, IP address not

Markus Freitag 3,791 Reputation points
2021-05-18T14:57:13.163+00:00

Hello,

localhost works, IP address not, why? How can I solve it?

 <appSettings>
    <add key="baseAddress" value="http://127.0.0.1:8888/" />    

    <!--<add key="baseAddress" value="http://localhost:8888/" />-->        

    <add key="url" value="" />

  </appSettings>  


 using (var request = new HttpRequestMessage(HttpMethod.Post, mesUri)) //$"{BaseAddress}{Url}"))
                    {

                        Log.Info($"[CUSTOM][PostBasis2], Adress= {requestUri}");

                        client.Timeout = TimeSpan.FromSeconds(3);

                        request.Version = HttpVersion.Version10; // Version11;
                        var json = JsonConvert.SerializeObject(content);

                        Log.Info($"[CUSTOM][PostBasis2], RequestMES=Object Post - Json\n\n{json}\n\n");

                        using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
                        {
                            request.Content = stringContent;

                            using (HttpResponseMessage response = client.PostAsync(requestUri, stringContent).Result)
                            {

I get an exception when I use the IP address. Why?

 client.PostAsync(requestUri, stringContent).Result
Developer technologies C#
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-05-19T02:14:45.2+00:00

    Unexpected character encountered while parsing value: <. Path'', line 0, position 0.

    This is an error when parsing Json, but it is caused by a data error in the response, so if we can solve the problem of Http error 400, this problem should disappear.

    Please check this link below, this post seems to have encountered the exact same problem:

    C# Web - localhost:port works, 127.0.0.1:port doesn't work

    But it should be noted that we should preset that such a situation may be encountered and handle exceptions.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.