How do I get around this error in my .net application

58 Views Asked by At

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

There are 1 best solutions below

0
Ponmani Chinnaswamy On

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;
    

    }