简体   繁体   English

如何从 C# Blazor WebAssembly 的 HttpClient 检索 cookies

[英]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?我知道它在服务器端 Blazor 上工作,但为什么不在装配类型中?

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;我在VS中按F10逐行调试代码,当它命中handler.CookieContainer = cookies; it will throw an exception that says, Property Container is not supported.它会抛出一个异常,说不Property Container is not supported. So how can I retrieve the cookies?那么如何检索 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. 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:我从 cookies 中读取了以下内容:

1.Inside js file: 1.内部js文件:

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: 2.内部组件:

 [Inject]  IJSRuntime _JSRuntime { get; set; }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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