类型' System.InvalidCastException'的例外情况发生了

时间:2015-06-08 13:15:55

标签: c# asp.net

错误消息:

  

类型' System.InvalidCastException'的例外情况发生在   test_login.dll但未在用户代码中处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace test_login
{
    public partial class home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            long user_id = (long)(Session["user_id"]);

            if (Session["user_id"] == null) { Response.Redirect("login.aspx"); return; }
            DBEntities ctx = new DBEntities();
            user user = ctx.users.First(u => u.user_id == user_id);
            lblOwnerName.Text = user.user_name;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

基于没有那么多信息,我可以看到一个可能的问题:

1. Session["user_id"]中的会话为空 总是建议检查你的会话是否仍然存在并使用安全演员:

if (Session["user_id"] == null)
{
    // session not exists
}
else
{
    long user_id;
    if(!long.TryParse(Session["user_id"].ToString(), out user_id))
    {
       // Handle sitiation if it is not possible to cast
    }
}