【问题标题】:How to retrieve cookies from an HttpClient from C# Blazor WebAssembly如何从 C# Blazor WebAssembly 的 HttpClient 检索 cookie
【发布时间】:2020-12-20 06:36:10
【问题描述】:

我一直试图找出我的代码有什么问题。我知道它在服务器端 Blazor 上运行,但为什么不使用 Assembly 类型?

我的代码是这样的。

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>();

我在VS中按F10逐行调试代码,当它点击handler.CookieContainer = cookies;时会抛出一个异常,上面写着Property Container is not supported.那么我怎样才能检索cookie? 只是为了给您提供上下文,Web API 不是 Restful,它是一项古老的技术,因此它只是基于简单的 http POST 请求并返回 xml 和一些 cookie 以确保安全。

【问题讨论】:

    标签: c# cookies blazor-client-side blazor-webassembly


    【解决方案1】:

    我做了以下从 cookie 中读取的操作:

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

     [Inject]  IJSRuntime _JSRuntime { get; set; }
    
    var cookieToeknValue = await _JSRuntime.InvokeAsync<string>("methods.getCookie", "CookieName);
    

    【讨论】:

    • cookie 来自 http 请求。因此,如果我可以从 HttpClient 获取它,我将使用 JavaScript 将其设置为浏览器 cookie。
    猜你喜欢
    • 2022-08-02
    • 2018-09-30
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2014-02-08
    • 2020-08-19
    • 2020-06-26
    • 2022-12-18
    相关资源
    最近更新 更多