Search code examples
c#asp.net-corecookiesasp.net-core-webapidotnet-httpclient

ASP.NET Core 7 API returns different from the web App


I have been struggling with this issue for days and would like some help with it. I am working on a web app where the UI is separated from the API logic. From UI I send some GET requests using the HttpClient.GetAsync function with the API URI as parameter.

public async Task<IActionResult> Index()
{
    string url;
    Dictionary<string, JsonDocument> admission = new Dictionary<string, JsonDocument>();

    // Check cookies
    string? cookie = Request.Cookies["Username"];

    if (cookie == null)
        return RedirectToAction("Index", "Home", new { area = "" });

    // Get areas
    url = $"{Request.Scheme}://{Request.Host}/api/Area";

    using (HttpClient client = new HttpClient())
    {
        using (HttpResponseMessage? response = await client.GetAsync(url))
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string apiResponse = await response.Content.ReadAsStringAsync();

                // Write data to JSON
                using (StreamWriter writer = new StreamWriter("wwwroot/json/AreaJson.json"))
                {
                    await writer.WriteAsync(apiResponse);
                }

                // Set JObject
                admission.Add("Areas", JsonDocument.Parse(apiResponse));
            }
        }
    }

On the API side, I am checking for a cookie to be set before sending back the response in a JSON string with a 200OK status.

[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Get()
{
    // Check cookies
    string? cookie = Request.Cookies["Username"];

    if (cookie == null)
    {
        return NotFound();
    }

    return Ok(JsonConvert.SerializeObject(new Dictionary<string, object>
    {
        { nameof(_service.DoctorOffices), _service.DoctorOffices },
        { nameof(_service.EmergencyRooms), _service.EmergencyRooms },
        { nameof(_service.LabRooms), _service.LabRooms },
        { nameof(_service.OperatingRooms), _service.OperatingRooms },
        { nameof(_service.PatientRooms), _service.PatientRooms },
        { nameof(_service.WaitingRooms), _service.WaitingRooms }
    }, Formatting.Indented));
}

If the cookie is null then I send the NotFound status code. The cookie is set from the UI side. So when I call the API uri from the browser, the result I get depends on whether I bypass the setting of the cookie or not and that works fine.

Capture

Capture

But when I make the call from the UI (by the GetAsync function, with the cookie set). I get the NotFound status code and I do not understand why.

Capture

Thanks in advance for any help.


Solution

  • Before sending the request to API, you should add the cookie value to the HttpRequestMessage.Headers as below:

    using (HttpClient client = new HttpClient())
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
        request.Headers.Add("Cookie", $"Username={cookie}");
    
        using (HttpResponseMessage? response = await client.SendAsync(url))
        {
            // Following implementation
        }
    }
    

    Alternatively, you can set the cookie to the request header via HttpClient.DefaultRequestHeaders.