C#Cookie无法型“字符串”转换为“X” [英] c# cookie cannot convert type 'string' to 'x'

查看:235
本文介绍了C#Cookie无法型“字符串”转换为“X”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的鳕鱼:

  [Serializable接口]
    公共类TESTC
    {
        串先生。
        公共TESTC()
        {
            先生=的String.Empty;
        }
        公共字符串的GetString
        {
            {返回先生。 }
            集合{先生=价值; }        }
    }
公共类为CookieTest
    {
        TESTC试验;
        公众为CookieTest()
        {
            测试=新TESTC();
        }
        公共TESTC GetTestC
        {
            得到
            {
                的HttpCookie饼干= HttpContext.Current.Request.Cookies [测试];
                测试=饼干[第一作为TESTC;
                回归测试;
            }
            组
            {
                的HttpCookie饼干=新的HttpCookie(测试);
                cookie.Expires = DateTime.Now.AddHours(8);
                饼干[第一] = value.ToString();
                System.Web.HttpContext.Current.Response.Cookies.Add(饼干);
            }
        }
    }

和我得到这个错误


  

无法通过引用转换类型字符串转换为TESTC,
  装箱转换,取消装箱转换,包装转换或null
  类型转换


有可能获得从cookie中的对象呢?还是必须写进去的cookie我的数据设置和获取所有数据,并创建一个新的对象来获取?


解决方案

  

有可能获得从cookie中的对象呢?


没有,不能直接作为你想。不要以为在ASP.NET中的条款。想想什么样的的HTTP cookie 是在现实条件。这是一个HTTP头。 HTTP标头是唯一的纯字符串值。对象的概念并不在HTTP协议中存在

所以,你需要序列化,你必须为一个字符串的.NET对象,然后反序列化回来。

有.NET中不同的序列化,你可以使用。例如使用的BinaryFormatter 然后 Base64编码的连接code 中生成的字节数组存储到该cookie。

反序列化的逆过程 - 你从Cookie读取(这始终是一个字符串)的值,那么你的 Base64的德code 它变成你使用反序列化回原对象的字节数组的BinaryFormatter

请记住,虽然该cookie的大小是有限的,不同的浏览器之间会有所不同。所以不要指望把大的物体进入饼干。该值将被剥离,你会得到损坏的数据。如果对象的序列化总价值超过2K字更大,我不会使用它们。

让我们举例说明的过程中更早:

 公共类为CookieTest
{
    TESTC试验;
    公众为CookieTest()
    {
        测试=新TESTC();
    }
    公共TESTC GetTestC
    {
        得到
        {
            VAR饼干= HttpContext.Current.Request.Cookies [测试];
            返回反序列化<&TESTC GT;(cookie.Value);
        }
        组
        {
            VAR饼干=新的HttpCookie(测试);
            cookie.Expires = DateTime.Now.AddHours(8);
            饼干[第一] =序列化(值);
            System.Web.HttpContext.Current.Response.Cookies.Add(饼干);
        }
    }    私人静态字符串序列化< T>(T实例)
    {
        使用(VAR流=新的MemoryStream())
        {
            VAR串行=新的BinaryFormatter();
            serializer.Serialize(流实例);
            返回Convert.ToBase64String(stream.ToArray());
        }
    }    私有静态ŧ反序列化< T>(字符串值)
    {
        使用(VAR流=新的MemoryStream(Convert.FromBase64String(值)))
        {
            VAR串行=新的BinaryFormatter();
            回报(T)serializer.Deserialize(流);
        }
    }
}

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无法型“字符串”转换为“X”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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