c#Cookie无法转换类型' string'到& x' [英] c# cookie cannot convert type 'string' to 'x'

查看:55
本文介绍了c#Cookie无法转换类型' string'到& x'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个鳕鱼:

  [可序列化]公开课测试{弦先生公开testC(){先生= string.Empty;}公共字符串GetString{得到{return sir;}设置{先生=值;}}}公共类cookieTest{testC测试;公共cookieTest(){测试=新的testC();}公共测试C GetTestC{得到{HttpCookie cookie = HttpContext.Current.Request.Cookies ["test"];test = cookie ["first"]作为testC;退货测试;}放{HttpCookie cookie =新的HttpCookie("test");cookie.Expires = DateTime.Now.AddHours(8);cookie ["first"] = value.ToString();System.Web.HttpContext.Current.Response.Cookies.Add(cookie);}}} 

我收到此错误

无法通过引用转换将类型字符串"转换为"testC",装箱转换,拆箱转换,换行转换或null类型转换

是否可以从cookie中获取对象?还是我必须将所有数据写入cookie来设置和获取所有数据,并创建一个新的对象来获取?

解决方案

是否可以从cookie中获取对象?

否,并非直接尝试那样.不要以ASP.NET的方式思考.考虑一下现实中的 HTTP cookie .这是一个HTTP标头.HTTP标头只是纯字符串值.HTTP协议中不存在对象的概念.

因此,您需要将拥有的.NET对象序列化为字符串,然后反序列化它.

.NET中可以使用不同的序列化程序.例如,使用 BinaryFormatter 然后 Base64编码将结果字节数组存储到cookie中./p>

反序列化是相反的过程-您从cookie(始终是字符串)中读取值,然后

I have this cod:

 [Serializable]
    public class testC
    {
        string sir;
        public testC()
        {
            sir = string.Empty;
        }
        public string GetString
        {
            get { return sir; }
            set { sir = value; }

        }
    }
public class cookieTest
    {
        testC test;
        public cookieTest()
        {
            test = new testC();
        }
        public testC GetTestC
        {
            get
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies["test"];
                test = cookie["first"] as testC;
                return test;
            }
            set
            {
                HttpCookie cookie = new HttpCookie("test");
                cookie.Expires = DateTime.Now.AddHours(8);
                cookie["first"] = value.ToString();
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
    }

And i get this error

Cannot convert type 'string' to 'testC' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

Is possible to get the object from cookie? Or I must to write into cookie all my data to set and get all data and create a new object to get?

Is possible to get the object from cookie?

No, not directly as you are trying to. Don't think in terms of ASP.NET. Think in terms of what an HTTP cookie is in reality. It is an HTTP header. HTTP headers are only plain string values. The notion of object doesn't exist in the HTTP protocol.

So you will need to serialize the .NET object that you have into a string and then deserialize it back.

There are different serializers in .NET that you could use. For example use the BinaryFormatter and then Base64 encode the resulting byte array to store into the cookie.

The deserialization is the inverse process - you read the value from the cookie (which is always a string), then you Base64 decode it into a byte array which you deserialize back to the original object using the BinaryFormatter.

Bear in mind though that the size of the cookies is limited and would vary between the different browsers. So don't expect to put large objects into cookies. The value will be stripped and you would get corrupt data. I wouldn't use them if the total serialized value of the object is larger than 2k characters.

Let's exemplify the process described earlier:

public class cookieTest
{
    testC test;
    public cookieTest()
    {
        test = new testC();
    }
    public testC GetTestC
    {
        get
        {
            var cookie = HttpContext.Current.Request.Cookies["test"];
            return Deserialize<testC>(cookie.Value);
        }
        set
        {
            var cookie = new HttpCookie("test");
            cookie.Expires = DateTime.Now.AddHours(8);
            cookie["first"] = Serialize(value);
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }

    private static string Serialize<T>(T instance)
    {
        using (var stream = new MemoryStream())
        {
            var serializer = new BinaryFormatter();
            serializer.Serialize(stream, instance);
            return Convert.ToBase64String(stream.ToArray());
        }
    }

    private static T Deserialize<T>(string value)
    {
        using (var stream = new MemoryStream(Convert.FromBase64String(value)))
        {
            var serializer = new BinaryFormatter();
            return (T)serializer.Deserialize(stream);
        }
    }
}

这篇关于c#Cookie无法转换类型&amp;#39; string&amp;#39;到&amp; x&amp;#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆