Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HttpClient post request throws exception "Couldn't connect to server" in ubuntu server #23754

Closed
victorchicu opened this issue Oct 6, 2017 · 7 comments
Labels
area-System.Net.Http os-linux Linux OS (any supported distro)
Milestone

Comments

@victorchicu
Copy link

The deployment I'm doing in ubuntu server in pair of Kestrel, Nginx e.t.c.
All the steps from this documentation: https://docs.microsoft.com/en-us/aspnet/core/publishing/linuxproduction?tabs=aspnetcore2x

Ubuntu information:
Distributor ID: Ubuntu
Description: Ubuntu 16.04.3 LTS
Release: 16.04
Codename: xenial

So, the problem as I see from the stack trace is exactly on the HttpClient initialization .cs line 34

Oct 06 05:43:12 smsassist smsassistservice[21050]: at SmsAssistKitchen.Managers.AccountManager.d__2.MoveNext() in D:\Startup projects\smsassistservice\SmsAssistKitchen\SmsAssistKitchen\Managers\AccountManager.cs:line 34

Full stack trace:

-- Logs begin at Thu 2017-10-05 11:34:12 UTC. --
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Net.Http.HttpClient.d__58.MoveNext()
Oct 06 05:43:12 smsassist smsassistservice[21050]: --- End of stack trace from previous location where exception was thrown ---
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Oct 06 05:43:12 smsassist smsassistservice[21050]: at SmsAssistKitchen.Managers.AccountManager.d__2.MoveNext() in D:\Startup projects\smsassistservice\SmsAssistKitchen\SmsAssistKitchen\Managers\AccountManager.cs:line 34
Oct 06 05:43:12 smsassist smsassistservice[21050]: --- End of stack trace from previous location where exception was thrown ---
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Oct 06 05:43:12 smsassist smsassistservice[21050]: at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Oct 06 05:43:12 smsassist smsassistservice[21050]: at SmsAssistKitchen.Controllers.AccountController.d__5.MoveNext() in D:\Startup projects\smsassistservice\SmsAssistKitchen\SmsAssistKitchen\Controllers\AccountController.cs:line 129

Here is example how I'm doing the request:

This static method is placed in static class so called AccountManager and this method is doing post request to another service to register an account.
This method is invoked from the post async controller you can see it a little below

public static async Task<HttpResponseMessage> RegisterAsync(AccountModel account)
        {
            using (var httpClient = new HttpClient())
                {
                    var jsonEntity = JsonConvert.SerializeObject(account);
                    var content = new StringContent(jsonEntity, Encoding.UTF8);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var response = await httpClient.PostAsync("http://127.0.0.1:8080/account/register", content);
                    return response;
                }     
        }
[HttpPost]
        public async Task<ActionResult> Register(AccountModel account)
        {
            try
            {
                logger.LogDebug("ModelState is valid? {0}", ModelState.IsValid);

                if (!ModelState.IsValid)
                {
                    logger.LogDebug("Going to response with a json result");
                    Response.StatusCode = (int)HttpStatusCode.Conflict;
                    var jsonResult = new JsonResult(JsonConvert.SerializeObject(new RegistrationResponseModel { Message = "Model state is invalid" }));
                    logger.LogDebug("Json result with serialized object. {0}", jsonResult.Value);
                    return jsonResult;
                }

                logger.LogDebug("Going to register new account {0}", account.Email);
                var responseMessage = await AccountManager.RegisterAsync(logger, account);

                logger.LogDebug("Response for account registration is: ");
                logger.LogDebug("StatusCode: {0}", responseMessage.StatusCode.ToString());
                logger.LogDebug("ReasonPhrase: {0}", responseMessage.ReasonPhrase);
                logger.LogDebug("IsSuccessStatusCode: {0}", responseMessage.IsSuccessStatusCode);
           
                switch (responseMessage.StatusCode)
                {
                    case HttpStatusCode.OK:
                        {
                            var content = await responseMessage.Content.ReadAsStringAsync();
                            var responseModel = JsonConvert.DeserializeObject<RegistrationResponseModel>(content);

                            HttpContext.Session.Set("access.token", Encoding.UTF8.GetBytes(responseModel.AccessToken.TokenString));

                            Response.StatusCode = (int)HttpStatusCode.OK;

                            var jsonResult = new JsonResult(JsonConvert.SerializeObject(new RegistrationResponseModel
                            {
                                Message = responseModel.Message,
                                AccessToken = responseModel.AccessToken
                            }));

                            return jsonResult;
                        }

                    case HttpStatusCode.Conflict:
                        {
                            var content = await responseMessage.Content.ReadAsStringAsync();

                            var responseModel = JsonConvert.DeserializeObject<RegistrationResponseModel>(content);

                            Response.StatusCode = (int)HttpStatusCode.Conflict;

                            var jsonResult = new JsonResult(JsonConvert.SerializeObject(new RegistrationResponseModel
                            {
                                Message = responseModel.Message,
                                AccessToken = responseModel.AccessToken
                            }));

                            return jsonResult;
                        }

                    default:
                        {
                            var content = await responseMessage.Content.ReadAsStringAsync();

                            var responseModel = JsonConvert.DeserializeObject<RegistrationResponseModel>(content);

                            Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                            var jsonResult = new JsonResult(JsonConvert.SerializeObject(new RegistrationResponseModel
                            {
                                Message = responseModel.Message,
                                AccessToken = responseModel.AccessToken
                            }));

                            return jsonResult;
                        }
                }
            }
            catch (Exception e)
            {
                logger.LogError("Was thrown an exception {0}", e.ToString());

                logger.LogDebug("Going to response with a json result");

                Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                var jsonResult = new JsonResult(JsonConvert.SerializeObject(new RegistrationResponseModel
                {
                    Message = e.Message,
                    AccessToken = null
                }));

                logger.LogDebug("Json result with serialized object. {0}", jsonResult.Value);

                return jsonResult;
            }
        }
@stephentoub
Copy link
Member

What kind of exception is it? What's its message? Inner exception?

@victorchicu
Copy link
Author

The shown stack trace is all that I have, more precisely this is all that was in systemctl status.
Let me check (in couple of hours) more info if I can

@victorchicu
Copy link
Author

victorchicu commented Oct 6, 2017

Ok, I got it.

Was thrown an exception System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.CurlException: Couldn't connect to server"

The interesting thing that the serivce where I do post request is pinging ok, telnet is ok. More over is on the same linux machine.
Locally in debug mode is working perfectly.

@victorchicu victorchicu changed the title HttpClient initialization throws an exception in ubuntu server HttpClient post request throws exception :Couldn't connect to server" in ubuntu server Oct 7, 2017
@victorchicu victorchicu changed the title HttpClient post request throws exception :Couldn't connect to server" in ubuntu server HttpClient post request throws exception "Couldn't connect to server" in ubuntu server Oct 7, 2017
@victorchicu
Copy link
Author

victorchicu commented Oct 7, 2017

Any ideas guys or provided information is not enough?

@stephentoub
Copy link
Member

pinging ok, telnet is ok

What about the actual port this would connect to? Are you able to make the same request using curl from the command line?

@victorchicu
Copy link
Author

Hi everyone, sorry for the delay and waste of your time.
Thanks stephentoub for the suggestion it was perfect because I forgot about the curl.
So, by the way I solved the problem cause I have seen that curl returns me unsupported type error.
For whom will have similar problem I just added right headers in the request and get it works like a charm.

 public async Task<HttpResponseMessage> RegisterAsync(AccountModel account)
        {
            try
            {
                logger.LogDebug("Going to initialize http client.");

                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var json = JsonConvert.SerializeObject(account);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync("http://127.0.0.1:8080/account/register", content);
                    return response;
                }

            }
            catch (Exception ex)
            {
                logger.LogError(ex.ToString());
                throw;
            }       
        }

The request is going to my java app and post method looks as following (also important thing do not forget to register JacksonFeature, for java developers just in case):

@POST
   @Path("/register")
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(MediaType.APPLICATION_JSON)
   public Response register(Account account) {
...
}

Thanks for everyone sorry again for my inattention and I think the issue can be closed. In any case is interesting why the Exception object told me one information like "Couldn't connect to the server" but there was completely different problem.

Best regards, Victor.

@stephentoub
Copy link
Member

Thanks, @loopnotzero.

@msftgits msftgits transferred this issue from dotnet/corefx Jan 31, 2020
@msftgits msftgits added this to the 2.1.0 milestone Jan 31, 2020
@dotnet dotnet locked as resolved and limited conversation to collaborators Dec 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-System.Net.Http os-linux Linux OS (any supported distro)
Projects
None yet
Development

No branches or pull requests

3 participants