获取SerializationException:'<> f__AnonymousType2`未标记为可序列化 [英] Getting SerializationException : '<>f__AnonymousType2` is not marked as serializable

查看:842
本文介绍了获取SerializationException:'<> f__AnonymousType2`未标记为可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的例外,当我在我的asp.net应用程序中调用一个WebMethod。而且我在sotring SQL服务器分贝我的会话;

 <的sessionState模式=SQLServer的
              allowCustomSqlDatabase =真
              sqlConnectionString =密码= Shiny365;数据源= 192.168.0.102;集成安全性= FALSE;初始目录=测试;用户ID = sa的超时=1440/>



这里是我的code;

  [的WebMethod]
[ScriptMethod(UseHttpGet =真)]
公共静态对象GetMenusByTabId(INT tabId)
{
    VAR menuManager =新MenuManager();
    清单< MenuManager>菜单= NULL;
    AgencyManager用户=(AgencyManager)HttpContext.Current.Session [UserCredential];
    如果(用户== NULL)
        返回新{状态= FALSE};
    菜单= menuManager.GetAllMenusByTabId(tabId,user.RoleId);
    HttpContext.Current.Session [MenusWithActivities] =菜单;
    清单< MenuManager> parentMenus =菜单
                                    。凡(M = GT; m.ParentId == 0)
                                    .ToList< MenuManager>();
    的foreach(在parentMenus VAR parentMenu)
    {
        parentMenu.Children =菜单
                                。选择(M =>新建
                                {
                                    的ParentId = m.ParentId,
                                    MENUID = m.MenuId,
                                    名称= m.Name,
                                    URL = m.Url,
                                    图标= m.Icon,
                                    ActivityView = m.ActivityView
                                })
                                。凡(M = GT; m.ParentId == parentMenu.MenuId&放大器;&安培; m.ActivityView == true)而
                                .ToList<对象>();
    }
    返回parentMenus.Select(M = GT;新
    {
        MENUID = m.MenuId,
        名称= m.Name,
        图标= m.Icon,
        儿童= m.Children
    });
}

我已经标记 MenuManager AgencyManager 为可序列化。

当我把这个的WebMethod ,我碰到下面的错误;

 无法序列化会话状态。在'的StateServer'和'的SQLServer模式,ASP.NET将序列化会话状态的对象,并因此不可序列化对象或对象MarshalByRef不允许。如果类似的序列化是通过在自定义模式自定义会话状态存储做了同样的限制也适用。
说明:执行当前Web请求的执行过程中发生未处理的异常。请查看有关错误的详细信息的堆栈跟踪以及它起源于code。异常详细信息:System.Web.HttpException:无法序列化会话状态。在'的StateServer'和'的SQLServer模式,ASP.NET将序列化会话状态的对象,并因此不可序列化对象或对象MarshalByRef不允许。如果类似的序列化是通过在自定义模式自定义会话状态存储做了同样的限制也适用。源错误:当前Web请求的执行过程中生成了未处理的异常。有关异常的来源和位置信息可以使用异常堆栈跟踪下面确定。堆栈跟踪:
[SerializationException:类型'<> f__AnonymousType2`6 [System.Int32,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089],[System.Int32,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089],[System.String,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089],[System.String,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089] [System.String,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089],[System.Boolean,mscorlib程序,版本= 4.0.0.0,文化=中性公钥= b77a5c561934e089]]'在大会'App_Web_oi13h5hv ,版本= 0.0.0.0,文化=中立,公钥=空'未标记为可序列。]
   System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType型)10458455
   System.Runtime.Serialization.FormatterServices.GetSerializableMembers(类型类型,的StreamingContext上下文)+230
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()+121
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(obj对象,ISur​​rogateSelector surrogateSelector,的StreamingContext上下文,SerObjectInfoInit serObjectInfoInit,IFormatterConverter来换算,ObjectWriter objectWriter,SerializationBinder粘合剂)+178
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(obj对象,ISur​​rogateSelector surrogateSelector,的StreamingContext上下文,SerObjectInfoInit serObjectInfoInit,IFormatterConverter来换算,ObjectWriter objectWriter,SerializationBinder粘合剂)+51
   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(对象图,标题[] inHeaders,__BinaryWriter serWriter,布尔FCHECK)+ 540
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(流serializationStream,对象图,标题[]头,布尔FCHECK)+131
   System.Web.Util.AltSerialization.WriteValueToStream(对象的价值,作家的BinaryWriter)1666[HttpException(0x80004005的):无法序列化会话状态。在'的StateServer'和'的SQLServer模式,ASP.NET将序列化会话状态的对象,并因此不可序列化对象或对象MarshalByRef不允许。如果类似的序列化是通过在自定义模式自定义会话状态存储做了同样的限制也适用。]
   System.Web.Util.AltSerialization.WriteValueToStream(对象的价值,作家的BinaryWriter)1754
   System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(对象的价值,作家的BinaryWriter)+34
   System.Web.SessionState.SessionStateItemCollection.Serialize(的BinaryWriter作家)628
   System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData项目,涧流)+240
   System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData项目的Int32 initialStreamSize,字节[]放大器; BUF,的Int32&安培;长度,布尔COM pressionEnabled)+62
   System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext的背景下,串ID,SessionStateStoreData项目,对象lockId,布尔的newitem)+135
   System.Web.SessionState.SessionStateModule.OnReleaseState(对象源,EventArgs的EventArgs的)798
   System.Web.SessionState.SessionStateModule.OnEndRequest(对象源,EventArgs的EventArgs的)+139
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()+136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep一步,布尔和放大器; completedSynchronously)+69


解决方案

事实上,匿名类型都没有标注 [Serializable接口] 。所以;如果框架您正在使用的需求序列化对象,则需要使用自己的类型,而不是匿名的。

在特定的,两个新{...} 有,即。

 返回parentMenus.Select(M = gt;新建SomeNewMenuTypeYouNeedToCreate
{
    MENUID = m.MenuId,
    名称= m.Name,
    图标= m.Icon,
    儿童= m.Children
});

  parentMenu.Children =菜单
    。选择(M =>新建AnotherMenuTypeYouNeedToCreate
    {
        的ParentId = m.ParentId,
        MENUID = m.MenuId,
        名称= m.Name,
        URL = m.Url,
        图标= m.Icon,
        ActivityView = m.ActivityView
    })
    。凡(M = GT; m.ParentId == parentMenu.MenuId&放大器;&安培; m.ActivityView == true)而
    .ToList<对象>();

请注意:如果你只是在类型名称添加,就可以得到Visual Studio创建的种类和添加的所有属性,只需使用<大骨节病> CTRL + 。 ,<大骨节病>⏎。那么你就需要添加 [Serializable接口] 来了两个新的类型。

i'm getting exception when i call a webmethod in my asp.net application. And i'm sotring my session in Sql Server Db;

<sessionState mode="SQLServer" 
              allowCustomSqlDatabase="true" 
              sqlConnectionString="Password=Shiny365;Data Source=192.168.0.102;Integrated Security=false;Initial Catalog=test;User ID=sa" timeout="1440"/>


here is my code;

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static object GetMenusByTabId(int tabId)
{
    var menuManager = new MenuManager();
    List<MenuManager> menus = null;
    AgencyManager user = (AgencyManager)HttpContext.Current.Session["UserCredential"];
    if (user == null)
        return new { status = false };
    menus = menuManager.GetAllMenusByTabId(tabId, user.RoleId);
    HttpContext.Current.Session["MenusWithActivities"] = menus;
    List<MenuManager> parentMenus = menus
                                    .Where(m => m.ParentId == 0)
                                    .ToList<MenuManager>();
    foreach (var parentMenu in parentMenus)
    {
        parentMenu.Children = menus
                                .Select(m => new
                                {
                                    ParentId = m.ParentId,
                                    MenuId = m.MenuId,
                                    Name = m.Name,
                                    Url = m.Url,
                                    Icon = m.Icon,
                                    ActivityView = m.ActivityView
                                })
                                .Where(m => m.ParentId == parentMenu.MenuId && m.ActivityView==true)
                                .ToList<object>();
    }
    return parentMenus.Select(m => new
    {
        MenuId = m.MenuId,
        Name = m.Name,
        Icon = m.Icon,
        Children = m.Children
    });
}

i have marked the MenuManager and AgencyManager as serializable.
When i call this WebMethod, i get the following error;

 Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[SerializationException: Type '<>f__AnonymousType2`6[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'App_Web_oi13h5hv, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
   System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +10458455
   System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +230
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +121
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +178
   System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +51
   System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +540
   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +131
   System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1666

[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
   System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1754
   System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +34
   System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +628
   System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +240
   System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +62
   System.Web.SessionState.SqlSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +135
   System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +798
   System.Web.SessionState.SessionStateModule.OnEndRequest(Object source, EventArgs eventArgs) +139
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69

解决方案

Indeed, anonymous types are not marked [Serializable]. So; if the framework you are using demands serializable objects, you will need to use your own types rather than anonymous ones.

In particular, the two new {...} there, i.e.

return parentMenus.Select(m => new SomeNewMenuTypeYouNeedToCreate
{
    MenuId = m.MenuId,
    Name = m.Name,
    Icon = m.Icon,
    Children = m.Children
});

and:

parentMenu.Children = menus
    .Select(m => new AnotherMenuTypeYouNeedToCreate
    {
        ParentId = m.ParentId,
        MenuId = m.MenuId,
        Name = m.Name,
        Url = m.Url,
        Icon = m.Icon,
        ActivityView = m.ActivityView
    })
    .Where(m => m.ParentId == parentMenu.MenuId && m.ActivityView==true)
    .ToList<object>();

Note: if you just add in the type names, you can get visual studio to create the types and to add all the properties, just by using ctrl+., . You would then need to add [Serializable] to the two new types.

这篇关于获取SerializationException:'&LT;&GT; f__AnonymousType2`未标记为可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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