如何在c# asp.net中减少字符串大小

本文关键字:字符串 net asp | 更新日期: 2023-09-27 18:14:55

我想在一个cookie中保存多个字符串值,大于4kb的字符串削减到1.3kb

这是我的代码- 通知 -我不确定代码是否正常工作,因为当我尝试在文本框中显示它们时没有cookie显示,不知道为什么。

编辑 - 保存cookie

protected void btnCookie_Click(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("cookie");
        cookie.Values.Add("cookie1", txtValue1.Text);
        cookie.Values.Add("cookie2", txtValue2.Text);
        cookie.Values.Add("cookie3", txtValue3.Text);
        cookie.Expires = DateTime.Now.AddDays(1d);
        Response.Cookies.Add(cookie);
        Response.Write("Success!");
    }

读取cookie

protected void btnLoadCookies_Click(object sender, EventArgs e)
    {
        if ((Request.Cookies["cookie"] != null))
        {
            TextBox1.Text = Request.Cookies["cookie"]["cookie1"];
            TextBox2.Text = Request.Cookies["cookie"]["cookie2"];
            TextBox3.Text = Request.Cookies["cookie"]["cookie3"];
        }
    }

你们能帮我创建一个函数/代码,将字符串大小从4kb减少到1.3kb吗?

谢谢!

如何在c# asp.net中减少字符串大小

你没有添加cookie:

    HttpCookie cookie = new HttpCookie("cookie");
    cookie.Values.Add("cookie1", txtValue1.Text);
    cookie.Values.Add("cookie2", txtValue2.Text);
    cookie.Values.Add("cookie3", txtValue3.Text);
    //  Now tell the Response about it
    Response.Cookies.Add(cookie);

很抱歉在评论中如此痛苦,但你最终基本上是自己弄清楚的。

如果最终需要截断文本,则需要String.Substring()。但是你也可以通过在三个不同的cookie中保存三个4k的文本块而不是在一个cookie中保存三个属性来给自己更多的喘息空间。