Add cookies to the API request in Blazor

I’m using the blazor web application with auto interaction and individual accounts, I’m trying to make a request to the API but the cookies aren’t passed on in the request, how do I add them?

return await _httpClient.GetFromJsonAsync<List<UserDTO>>("api/users");

I need suggestions, I’ve been trying to solve this problem for some time, but without success.

7

There is no built-in way for the demand. You will need to get the authentication cookie on your own. After login, then asp.net core identity cookie will be generated to the domain with the cookie name .AspNetCore.Identity.Application

Then you need to get the cookie before httpclient request. WASM will experience 2 rendermodes: prerender and interactive. (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0#ihttpcontextaccessorhttpcontext-in-razor-components-blazor)
When prerender : HttpContext is available. Js Interop not available. You could get cookie by httpContext.request.cookie.
When interactive : HttpContext is not available. Js Interop is available. You could get cookie by javascript “document.cookie”.

So you could do following :
Install Microsoft.AspNetCore.Http 2.2.2 at client project, then call backend in an WASM page like

@page "/counter"
@using Microsoft.AspNetCore.Http
@rendermode InteractiveWebAssembly

@inject IJSRuntime _js

@data

<script>
    function ReadCookie(name) {
        const value = `; ${document.cookie}`;   
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }
</script>


@code {
    string data = "";
    [CascadingParameter]
    HttpContext? httpContext{ get; set; }


    protected override async Task OnInitializedAsync()
    {
        string authcookie;
        if (httpContext != null)
        {
            //when prerender get cookie from httpContext
            authcookie = httpContext.Request.Cookies[".AspNetCore.Identity.Application"];
        }
        else
        {
            //when interactive get cookie by js interop
            authcookie = await _js.InvokeAsync<string>("ReadCookie", ".AspNetCore.Identity.Application");
        }


        if (authcookie != null)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7264/test"); //the [Authorize] webapi endpoint
            // Add a cookie to the request headers
            request.Headers.Add("Cookie", $".AspNetCore.Identity.Application={authcookie}");

            // Send the request
            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                data = await response.Content.ReadAsStringAsync();
            }
        }
        else
        {
            data = "no authentication cookie";
        }
    }
}

Need to set cookie httponly to false in server project program.cs.

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = false;
});

12

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật