0

This is my error

SocketException: No connection could be made because the target machine actively refused it.

I am getting it on this code

public class AppService : IAppService
{
    public async Task<MainResponse> AuthenticateUser(LoginModel loginModel)
    {
        var returnResponse = new MainResponse();

        using (var client = new HttpClient())
        {
            var url = $"{Setting.BaseUrl}{UserAPIs.AuthenticateUser}";

            var serializedStr = JsonConvert.SerializeObject(loginModel);

            var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));

            if (response.IsSuccessStatusCode)
            {
                string contentStr = await response.Content.ReadAsStringAsync();
                returnResponse = JsonConvert.DeserializeObject<MainResponse>(contentStr);
            }
        }

        return returnResponse;
    }
}

This is my controller code for the API All of my port numbers are right and all other API's are running correctly I just cant get passed the log in with the username and password

    [AllowAnonymous]
    [HttpPost("AuthenticateUser")]
    public async Task<IActionResult> AuthenticateUser(LoginModel authenticateUser)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(authenticateUser.UserName);
            if (user == null) return Unauthorized();

            bool isValidUser = await _userManager.CheckPasswordAsync(user, authenticateUser.Password);

            if (isValidUser)
            {
                string accessToken = GenerateAccessToken(user);
                var refreshToken = GenerateRefreshToken();
                await _userManager.UpdateAsync(user);

                var role = await _userManager.GetRolesAsync(user);

                int? roleID = null;
                switch (role?.FirstOrDefault())
                {
                    case "Admin":
                        roleID = (int)RoleEnum.Admin;
                        break;
                    case "Student":
                        roleID = (int)RoleEnum.Student;
                        break;
                    case "Teacher":
                        roleID = (int)RoleEnum.Teacher;
                        break;
                }

                var response = new MainResponse
                {
                    Content = new AuthenticationResponse
                    {
                        RefreshToken = refreshToken,
                        AccessToken = accessToken,
                        RoleID = roleID
                    },
                    IsSuccess = true,
                    ErrorMessage = ""
                };
                return Ok(response);
            }

            else
            {
                return Unauthorized();
            }
        }
        catch (Exception ex)
        {
            var response = new MainResponse
            {
                Content = new AuthenticationResponse
                {
                    RefreshToken = null,
                    AccessToken = null,
                    RoleID = null,
                    DeviceToken = null
                },
                IsSuccess = true,
                ErrorMessage = ex.Message
            };
            return Ok(response);
        }
    }
  • Try this: [https://stackoverflow.com/questions/2972600](https://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it) – Denis Kiryanov Aug 07 '23 at 10:56
  • This typically occurs when the API is not running (or where you expect it to run). Are you sure the API your calling is up and running at the specified URL. Check domain and port. – Mushroomator Aug 07 '23 at 10:56
  • Does this answer your question? [No connection could be made because the target machine actively refused it?](https://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it) – Mushroomator Aug 07 '23 at 10:57

1 Answers1

0

Try these..

  1. Make sure the API is Up.

  2. Check the URL

  3. Add exception handling in your code

    public async Task AuthenticateUser(LoginModel loginModel) { var returnResponse = new MainResponse();

    try
    {
        using (var client = new HttpClient())
        {
            var url = $"{Setting.BaseUrl}{UserAPIs.AuthenticateUser}";
    
            var serializedStr = JsonConvert.SerializeObject(loginModel);
    
            var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
    
            if (response.IsSuccessStatusCode)
            {
                string contentStr = await response.Content.ReadAsStringAsync();
                returnResponse = JsonConvert.DeserializeObject<MainResponse>(contentStr);
            }
        }
    }
    catch (Exception ex)
    {
        // Log or display the exception details for troubleshooting.
        Console.WriteLine($"Error: {ex.Message}");
        // You can also throw the exception if needed.
        // throw;
    }
    
    return returnResponse;
    

    }