2013-03-29 33 views
32

我得到的错误是:错误 - 没有标记为可序列

Type 'OrgPermission' in Assembly 'App_Code.ptjvczom, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 

这里是我的代码:

我有一个GridView,使用以下数据源:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetOrgList" 
      TypeName="Org"> 
    <SelectParameters> 
     <asp:SessionParameter Name="orgCodes" SessionField="UserOrgs" Type="Object" /> 
     <asp:Parameter DefaultValue="Y" Name="active" Type="String" /> 
    </SelectParameters> 
</asp:ObjectDataSource> 

我在我的页面加载中设置会话变量,如下所示:

User cUser = new User(userid); 
//make sure the user is an Admin 
List<OrgPermission> orgs = new List<OrgPermission>(); 
foreach(OrgPermission org in cUser.orgs) 
    { 
    if (org.type=='admin') 
    { 
     orgs.Add(org);      
    } 
    } 
Session["UserOrgs"] = orgs; 

我的用户类看起来是这样的:

public class OrgPermission 
{ 
    public string Org { get; set; } 
    public List<string> type { get; set; } 

    public OrgPermission() 
    { }  
} 
public class cUser 
{  
    public string userid { get; set; } 
    public List<OrgPermission> orgs { get; set; } 

    public clsUser(string username) 
    { 
     //i set everything here 
    } 
} 

我不明白为什么它打破,我可以用它没有使它序列化?

我试着调试,会话变量设置得很好,然后进入GetOrgList并返回正确的结果,但页面没有加载,我得到上面的错误。

这里是我的GetOrgList功能的一个片段:

public DataTable GetOrgList(List<OrgPermission> orgCodes, string active) 
    { 

     string orgList = null; 

     //code to set OrgList using the parameter is here. 

     DataSet ds = new DataSet(); 
     SqlConnection conn = new SqlConnection(cCon.getConn()); 
     SqlCommand cmd = new SqlCommand("sp_GetOrgList", conn); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.Add(new SqlParameter("@orgList", orgList)); 
     cmd.Parameters.Add(new SqlParameter("@active", active)); 

      conn.Open(); 
      SqlDataAdapter sqlDA = new SqlDataAdapter(); 

      sqlDA.SelectCommand = cmd; 
      sqlDA.Fill(ds); 

      conn.Close(); 
     return ds.Tables[0]; 
    } 

回答

104
[Serializable] 
public class OrgPermission 
+1

做到了。谢谢!我想我仍然有办法学习。 –

+11

同样重要的是*为什么*您必须添加可序列化的标签:放入会话变量(除了基本对象,如int和bools)的任何对象都必须标记为可序列化。请注意,某些.NET类不是默认的 - 即DataView。 – Paul

+0

我已经将我的列表类型对象类型存储在'Viewstate'中,并且当我尝试将它用作DataSource作为中继器控件时,它向我展示了同样的错误。它是否也适用于ViewState和Session State? – sohaiby

12

如果您存储在会话状态的对象,该对象必须是可序列化。

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/asp_dotnet_bad_practices_non_serializable_object_stored_in_session.html


编辑:

为了使会话被正确串行化时,所有对象的应用商店作为会话属性必须声明[Serializable]属性。此外,如果对象需要自定义序列化方法,则它还必须实现ISerializable接口。

https://vulncat.hpefod.com/en/detail?id=desc.structural.dotnet.asp_dotnet_bad_practices_non_serializable_object_stored_in_session#C%23%2fVB.NET%2fASP.NET

+0

不适用于Mode = InProc – Roland

+0

无法找到您请求的页面。 – JoshYates1980

相关问题