【问题标题】:Getting SerializationException : '<>f__AnonymousType2` is not marked as serializable获取 SerializationException:'<>f__AnonymousType2` 未标记为可序列化
【发布时间】:2013-08-20 07:54:40
【问题描述】:

当我在我的 asp.net 应用程序中调用 webmethod 时出现异常。我正在 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"/>


这是我的代码;

[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
    });
}

我已将MenuManagerAgencyManager 标记为可序列化。
当我调用此 WebMethod 时,出现以下错误;

 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

【问题讨论】:

  • 与您的最后一条语句 return parentMenus.Select(m => new... 您正在返回一个未标记为可序列化的匿名类型。
  • if (user == null) return new { status = false };select new ... 这是导致麻烦的代码,您不能传递超出 AppDomain Boundaries 的匿名类型
  • @gsharp,你是对的。当我尝试返回return new object { }; 时,它可以工作。但是我有很多返回匿名类型的代码。我需要一个简单的解决方案。
  • @DotNetDreamer 你不能返回 json 吗?如果不是,恐怕你必须生成你的类
  • @gsharp,现在我得到了解决方案。但我会尝试返回 json。谢谢你的时间:)

标签: c# asp.net serialization


【解决方案1】:

确实,匿名类型没有标记为[Serializable]。所以;如果您使用的框架需要可序列化的对象,您将需要使用自己的类型而不是匿名类型。

特别是那里的两个new {...},即

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

和:

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

注意:如果你只是添加类型名称,你可以让visual studio创建类型并添加所有属性,只需使用ctrl+ , 。然后,您需要将[Serializable] 添加到这两种新类型中。

【讨论】:

  • 还有:return new { status = false };
  • 我为最后一个代码定义了一个类型(在你的答案中),现在它可以工作了。但是,我还没有为第一个代码定义一个类型(在你的答案中)并且它仍然有效
【解决方案2】:

C# 中的匿名类型未标记为可序列化。此外,如果您发回一个令人讨厌的类型,那么任何人都知道如何反序列化它,因为类型是未知的。

【讨论】:

  • 实际上,除了BinaryFormatter 选择 来强制执行[Serializable] 属性(其中技术上实际上并没有作为属性实现 - 不,真的)。 BinaryFormatter 会知道类型并能够以任何一种方式对其进行反序列化,调用者可以将其视为objectdynamic,或者使用反射,或者使用cast-by-example。注意:我在这里不是支持 BinaryFormatter(我仍然认为使用BinaryFormatter 几乎总是错误的);p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 2017-02-21
  • 2015-11-10
  • 2016-01-18
  • 2011-01-17
  • 1970-01-01
相关资源
最近更新 更多