Search code examples
c#asp.net-core-mvcasp.net-core-webapi.net-core-3.1

.NET Core 3.1: No connection could be made because the target machine actively refused it


I am working on a .net core web app code challenge and I am getting the following error:

An unhandled exception occurred while processing the request. SocketException: No connection could be made because the target machine actively refused it. System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)

The code is in this repo

The error is occurring in this method:

public async Task<TeamDTO> AddTeam(string teamName)
{
    var client = _httpClientFactory.CreateClient();
    client.BaseAddress = new Uri(_baseUri);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var team = new TeamDTO { Name = teamName };
    var response = await client.PostAsync("teams", new StringContent(JsonSerializer.Serialize(team), Encoding.UTF8, "application/json"));
    response.EnsureSuccessStatusCode();
    var responseBody = await response.Content.ReadAsStringAsync();
    return JsonSerializer.Deserialize<TeamDTO>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}

On this line of code:

var response = await client.PostAsync("teams", new StringContent(JsonSerializer.Serialize(team), Encoding.UTF8, "application/json"));

I am trying to connect to this API method:

    [HttpPost("Post")]
    public virtual ActionResult<GameDTO> Post(GameDTO gameDTO)
    {
        var game = new Game
        {
            HomeTeamId = gameDTO.HomeTeamId,
            AwayTeamId = gameDTO.AwayTeamId,
            Date = gameDTO.Date,
            WinningTeamId = gameDTO.WinningTeamId
        };
        game.Id = Repository.Insert(game);

        return Ok(gameDTO);
    }

I am running VS 2022 on Windows 11 pro. I am using IIS Express and launching both applications from the same VS 2022 solution. I have thoroughly tested (there are unit tests) the API code and it works. The API and the web app both launch. Everything works fine until I click Add Team in the games view of the web app, then the code shown above is hit etc. I believe this is a configuration issue.


Solution

  • I am using IIS Express and launching both applications from the same VS 2022 solution. I have thoroughly tested (there are unit tests) the API code and it works. The API and the web app both launch

    You said you are using IIS Express ,but port of the base uri doesn't match;

    "ApiSettings": { "BaseUri": "localhost:5000" },
    
     _baseUri = configuration["ApiSettings:BaseUri"];
    

    modify 5000 to the port of your api project(20269) when you run it in IIS Express