2013-03-29 31 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

相關問題