Search code examples
c#asp.net-mvccontrollerdotnet-httpclient

ASP.NET MVC Core - Consume API through HttpClient


I have a Visual Studio solution with two projects; API and MVC. MVC is my MVC-project containing my views etc., API is my API-project containing the API-endpoints and logic. Since I have two projects, I have configured my solution to have multiple startup-projects.

HttpClient

public const string AuctionAPI = "http://localhost:44337/";
public const string AuctionClient = "http://localhost:44398/";

public static HttpClient GetClient()
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(AuctionAPI);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    return client;
}

MVC Controller (Notice: I receive the error on line 6, when I set HttpResponseMessage and try to call client.GetAsync()

[Route("item/{itemNumber}")]
public async Task<IActionResult> IndexForItem(int itemNumber)
{
    var client = GetClient();
    //ERROR: In next line, HttpResponseMessage it tries to call my API controller and fails
    HttpResponseMessage response = await client.GetAsync($@"api/Auction/SeeOneItem/{itemNumber}");

    if (response.IsSuccessStatusCode)
    {
        string content = await response.Content.ReadAsStringAsync();
        var model = await response.Content.ReadAsAsync<AuctionItemProxy>();

        return View(model);
    }
    else
    {
        return Content("An error occured.");
    }
}

API Controller (Notice: my breakpoint in this method never hits)

[HttpGet("SeeOneItem/{itemNumber:int}")]
public AuctionItem GetAuctionItem(int itemNumber)
{
    var item = _auctionItemDataFactory.AuctionItems.First(x => x.ItemNumber == itemNumber);
    if (item == null)
    {
        return null;
    }
    return _auctionItemDataFactory.AuctionItems.First(x => x.ItemNumber == itemNumber);
}

Actual error I receive

IOException: Unable to read data from the transport connection


Solution

  • This error means that the target machine is accessible but the service you are trying to reach is not accessible.

    By looking at your code you shared I noticed one thing. If the project is set up to use Https then IIS Express assigns ports starting with 443 resulting in a port like 443xx. Change your http scheme to https and try again.

    public const string AuctionAPI = "http://localhost:44337/";
    

    to

    public const string AuctionAPI = "https://localhost:44337/";
    

    OR

    Change your project settings to not use SSL

    1. Right Click your project Go to properties
    2. In properties window go to Debug section
    3. Under Web Server Settings un-check "Enable SSL"

    This issue can also be related to transport level security.