简体   繁体   中英

How to retrieve cookies from an HttpClient from C# Blazor WebAssembly

I've been trying to figure out what's wrong with my code. I know that it's working on server-side Blazor but why not in an Assembly type?

My code goes like this.

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient authClient = new HttpClient(handler);

var requestMessage = new HttpRequestMessage(HttpMethod.Post, theUrl) { Content = new FormUrlEncodedContent(dict) };

var responseCookies = cookies.GetCookies(theUrl).Cast<Cookie>();

I debug the code line by line by pressing F10 in VS, when it hit handler.CookieContainer = cookies; it will throw an exception that says, Property Container is not supported. So how can I retrieve the cookies? Just to give you the context, the web API is not Restful and it's an old technology so it's just based on simple http POST request and returns xml and some cookies for security.

I did the following to read from cookies:

1.Inside js file:

window.methods = {
    getCookie: function (cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
  

2.Inside Component:

 [Inject]  IJSRuntime _JSRuntime { get; set; }

var cookieToeknValue = await _JSRuntime.InvokeAsync<string>("methods.getCookie", "CookieName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM