System.NullReferenceException: '未将对象引用设置到对象的实例。'

刚学不久,自己写一个小项目,出现了这个异常
不知道是不是Session["UserId"]引起的
上网搜到一些解决方法试了试还是不成功
想请大家帮忙看一看

Controller下的ActionResult
//Update Picture
[HttpPost]
public ActionResult UpdatePicture(PictureVM obj)
{
int userId = Convert.ToInt32(Session["UserId"]);
if (userId == 0)
{
return RedirectToAction("Login", "Account");
}

        var file = obj.Picture;
        User u = db.Users.Find(userId);
        if( file != null)
        {
            //update the img
            var extension = Path.GetExtension(file.FileName);
            string id_and_extension = userId + extension;
            string imgUrl = "~/Profile_Images/" + id_and_extension;
            u.ImageUrl = imgUrl;
            db.Entry(u).State = EntityState.Modified; //*
            db.SaveChanges();

            var path = Server.MapPath("~/Profile_Images/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path + id_and_extension);
            }
            //when update new img, delete old img
            if ((System.IO.File.Exists(path + id_and_extension))) //imgUrl
            {
                System.IO.File.Delete(path + id_and_extension);
            }
            file.SaveAs((path + id_and_extension));
        }
        return RedirectToAction("UserProfile");
    }
UserProfile.cshtml下关于ImageUrl的部分
        <dt>
            @Html.DisplayNameFor(model => model.ImageUrl)
        </dt>
        <dd style="margin-top:15px">
            @*@if(Model.ImageUrl.Length > 0)*@
            @*System.NullReferenceException: '未将对象引用设置到对象的实例。'
            ClairG.ChatApp.Domain.Entities.User.ImageUrl.get returned null.*@
            @if (Model.ImageUrl != null)  //无法保存图片
            {
                <img src="@Url.Content(Model.ImageUrl)" alt="No Image" style="height:200px" class="img-responsive img-circle" />
            }
            <br /><br />
            @using (Html.BeginForm("UpdatePicture", "User", FormMethod.Post,
                new { enctype = "multipart/form-data" }))
            {
                <input type="file" name="Picture class=" col-sm-2 form-control"" />
                <input type="submit" value="Save Image" class="btn btn-default" />
            }
        </dd>

3个回答

User u = db.Users.Find(userId);
看下这个是不是空的

lemonmon0111
宁檬檬 谢谢,设置断点跑了一遍成功了,可能是缓存的问题。。。
5 个月之前 回复

要调试的方式运行(F5)或者选择调试菜单-启动。
然后找到报错的行,再看具体是什么变量NULL了。

lemonmon0111
宁檬檬 设置断点,没有修改代码,跑了一遍成功了。。。
5 个月之前 回复
    var file = obj.Picture;
    User u = db.Users.Find(userId);

            看obj是不是null, 或者看db.Users是不是null
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
iis6.0 System.NullReferenceException: 未将对象引用设置到对象的实例
未将对象引用设置到对象的实例。 rn说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrnrn行 122: rn行 123: //使用版块rn行 124: if ((config.Iisurlrewrite == 1 || config.Aspxrewrite == 1) && requestPath.EndsWith("/list.aspx") &&rn行 125: requestPath.IndexOf("/archiver/") < 0 && requestPath.IndexOf("/install/") < 0 && requestPath.IndexOf("/upgrade/") < 0 &&rn行 126: requestPath.IndexOf("/admin/") < 0 && requestPath.IndexOf("/aspx/") < 0 && requestPath.IndexOf("/tools/") < 0 &&rn rnrn源文件: D:\BBSProjects\XL.Forum\HttpModule.cs 行: 124 rnrn堆栈跟踪: rnrnrn[NullReferenceException: 未将对象引用设置到对象的实例。]rn XL.Forum.HttpModule.ReUrl_BeginRequest(Object sender, EventArgs e) in D:\BBSProjects\XL.Forum\HttpModule.cs:124rn System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +213rn System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +76rnrn rnrnrn--------------------------------------------------------------------------------rn版本信息: Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.0.30319.1 rnrn疑惑:rn我在vs2008 调试的时候就没有这个异常,为什么部署到iis中就出现了这个异常呢?rn希望老师给我个解答。
System.NullReferenceException: 未将对象引用设置到对象的实例 的疑问??
各位大虾,小弟菜鸟,编译的时候出了这个问题可能是什么地方有问题了??恳请各位大虾指点一番~~不胜感激~~rnrnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrnrn行 148: break;rn行 149: rn[color=#FF0000]行 150: SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);[/color]行 151: SqlCommand cmd = new SqlCommand(selectStr, conn);rn行 152: tryrn rnrn源文件: e:\新建文件夹\Visual Studio 2005\Projects\0600220229-01\15977448344\denglu.aspx.cs 行: 150
System.NullReferenceException: 未将对象引用设置到对象的实例
float[] a = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ;rnbyte[] pReadBuffer = new byte[184];rnZSPLC.ReadByteFromDB(1, 8, 184, out pReadBuffer);rnfor (int i = 0; i < 10; i++)rn rn int b = 20 * i;rn byte[] c =new byte[4] pReadBuffer[b + 3], pReadBuffer[b + 2], pReadBuffer[b + 1], pReadBuffer[b] ;rn a[i] = System.BitConverter.ToSingle(c, 0);rn DataClass.RealData[i] = a[i];rn rn rn运行以上代码 出现如题的错误。刚开始能正常运行,但在一段不确定的时间后就会出错。
System.NullReferenceException: 未将对象引用设置到对象的实例。
源错误: rnrnrn行 33: ObjXml.Load(StrSourceFile)rn行 34: ObjRootSite=ObjXml.DocumentElement.SelectSingleNode("Newlist")rn行 35: AllNodesNum=ObjRootSite.ChildNodes.count '这一行错误rn行 36: PageNum=AllNodesNum\Pagesize + 1rn行 37: pg.Value=1rn rnrn源文件: D:\ASP.NET\ASPNETEXM\gbook\index.aspx 行: 35 rnrn堆栈跟踪: rnrnrn[NullReferenceException: 未将对象引用设置到对象的实例。]rn ASP.index_aspx.Page_Load(Object sender, EventArgs e) in D:\ASP.NET\ASPNETEXM\gbook\index.aspx:35rn System.Web.UI.Control.OnLoad(EventArgs e) +55rn System.Web.UI.Control.LoadRecursive() +21rn System.Web.UI.Page.ProcessRequestMain() +724rnrnrn怎么办?rn rn
求救:System.NullReferenceException: 未将对象引用设置到对象的实例
请各位高人指点迷津,不胜感谢!rn//测试给出的密码是否正确rnpublic bool TestPassword(string pass)rn rn byte[] encryptPass=user.Encrypt(pass); rn for (int i = 0; i
急 System.NullReferenceException: 未将对象引用设置到对象的实例。
错误详细:rnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrnrn行 13: rn行 14: MessageInterface iMsg = MessageFactory.Create();rn[color=#FF0000]rn行 15: return iMsg.AddMessage(message);rn[/color]rn行 16: rn行 17: rn rnrn源文件: F:\GameDesign\Bussiness\MessageBusiness.cs 行: 15 rnrnrn运行页面后台代码:rn[code=C#]rnusing System;rnusing System.Collections;rnusing System.Configuration;rnusing System.Data;rnusing System.Web;rnusing System.Web.Security;rnusing System.Web.UI;rnusing System.Web.UI.HtmlControls;rnusing System.Web.UI.WebControls;rnusing System.Web.UI.WebControls.WebParts;rnusing System.IO;rnusing GD.Model;rnusing GD.DataAccess;rnusing GD.SystemFrameworks;rnusing GD.Bussiness.Message;rnrnpublic partial class AddMsg : System.Web.UI.Pagernrn protected void Page_Load(object sender, EventArgs e)rn rn if (Session["fld_UserName"] == null)rn rn this.Response.Write(" ");rn Response.Redirect("Login.aspx?message=" + Server.UrlEncode("请登录后再留言!"));rn rn //if (!CommonClass.hasSession(Page.Session))rn // Response.Redirect("Login.aspx?message=" + Server.UrlEncode("请登录后再留言!"));rn rnrn protected void btnOK_Click(object sender, EventArgs e)rn rnrn Message message = new Message();rn message.fld_UserId = Convert.ToInt32(Label1.Text);rn message.fld_Title = txtTitle.Text;rn message.fld_Content = txtDSC.Text;rn message.fld_CreatedTime = Convert.ToDateTime(DateTime.Now);rnrn MessageBusiness messageBusiness = new MessageBusiness();rn if (messageBusiness.AddMessage(message))rn rn Utility.AlertMsg(this.Page, "成功");rn rn elsern rn Utility.AlertMsg(this.Page, "失败");rn rn rnrn[/code]rnrn业务层代码:rn[code=C#]rnnamespace GD.Bussiness.Messagernrn using System;rn using System.Data;rn using System.Collections.Generic;rn using System.Text;rn using GD.Model;rn using GD.DataAccess.Message;rnrn public class MessageBusinessrn rn public bool AddMessage(Message message)rn rn MessageInterface iMsg = MessageFactory.Create();rn return iMsg.AddMessage(message);rn rn rnrn[/code]rnrn数据处理代码:rn[code=C#]rnnamespace GD.DataAccess.Messagernrn using System;rn using System.Data;rn using System.Data.SqlClient;rnrn using GD.Model;rn using GD.SystemFrameworks;rn using GD.DataAccess.SystemFrame;rnrn public class MessageSqlHandle : MessageInterfacern rn public bool AddMessage(Message message)rn rn SQLHelper helper = new SQLHelper();rn SqlParameter[] prams = rn new SqlParameter("@fld_UserId",SqlDbType.Int,8),rn new SqlParameter("@fld_Title",SqlDbType.NVarChar,50),rn new SqlParameter("@fld_Content",SqlDbType.NVarChar),rn new SqlParameter("@fld_CreatedTime",SqlDbType.DateTime,8)rn ;rn prams[0].Value = message.fld_UserId;rn prams[1].Value = message.fld_Title;rn prams[2].Value = message.fld_Content;rn prams[3].Value = message.fld_CreatedTime;rnrn int i;rn i = helper.ExecuteNonQuery("Tb_AddMessage", prams);rn if (i == 0)rn return true;rn elsern return false;rn rn rnrn[/code]rn存储过程:rn[code=SQL]rnALTER PROCEDURE dbo.Tb_AddMessagern (rn @fld_UserId int,rn @fld_Title nvarchar(100),rn @fld_Content nvarchar(max),rn @fld_CreatedTime datetime,rn @fld_Clicks intrn )rnASrnBEGINrn BEGIN TRYrn INSERT INTO Tb_Message(rn fld_UserId,rn fld_Title,rn fld_Content,rn fld_CreatedTime,rn fld_Clicksrn )VALUES(rn @fld_UserId,rn @fld_Title,rn @fld_Content,rn @fld_CreatedTime,rn @fld_Clicksrn )rn rn RETURN 0rn END TRYrn BEGIN CATCHrn RETURN ERROR_NUMBER()rn END CATCHrnrnENDrn[/code]rnrn工厂反射模式 的程序 折腾了一下午了 始终解决不了 急啊~~~rn
System.NullReferenceException:未将对象引用设置到对象的实例
//自定义ResultInfo()方法,实现提取指定信息,并将其显示在相应的文本框控件中,可是显示未将对象引用设置到对象的实例,排错了好长时间,无果,就高手指点rn private void ResultInfo(int j)rn rn tryrn rn DataSet dsNew = DtReslut(j);rn this.txbClassName.Text = dsNew.Tables[0].Rows[0][0].ToString();//出错的地方rn this.txbClassNumber.Text = dsNew.Tables[0].Rows[0][1].ToString();rn this.txbGrade.Text = dsNew.Tables[0].Rows[0][2].ToString();rn this.txbShortName.Text = dsNew.Tables[0].Rows[0][3].ToString();rn this.txbTeacher.Text = dsNew.Tables[0].Rows[0][4].ToString();rn this.txbNo.Text = dsNew.Tables[0].Rows[0][5].ToString();rn rn catch (Exception ex)rn rn MessageBox.Show(ex.Message);rn rnrn
异常!System.NullReferenceException: 未将对象引用设置到对象的实例
[code=csharp] rn//========================= ItemDTO 定义 rnpublic class ItemDTOrn rn public int id;rn public int itemId;rn public int itemNum;rn public string outTime;rn public int roleId;rn public int storageType;rn rn//========================= GardenSeed 定义 rnpublic class GardenSeed : ObjBasern rn public int SeedTimern rn getrn rn return Convert.ToInt32(base.Columns["SeedTime"].Value);rn rn setrn rn base.Columns["SeedTime"].Value = value;rn rn rn public string SeedGetMoneyrn rn getrn rn return Convert.ToString(base.Columns["SeedGetMoney"].Value);rn rn setrn rn base.Columns["SeedGetMoney"].Value = value;rn rn rn public int IDrn rn getrn rn return Convert.ToInt32(base.Columns["ID"].Value);rn rn setrn rn base.Columns["ID"].Value = value;rn rn rn public int SeedIDrn rn getrn rn return Convert.ToInt32(base.Columns["SeedID"].Value);rn rn setrn rn base.Columns["SeedID"].Value = value;rn rn rn public GardenSeed()rn rn base.TableName = "GardenSeed";rn base.AddColumn(new Column("SeedTime", ColumnType.Int));rn base.AddColumn(new Column("SeedGetMoney", ColumnType.String));rn base.AddColumn(new Column("ID", "0", ColumnType.Int, true, IdentityType.Normal));rn base.AddColumn(new Column("SeedID", ColumnType.Int));rn rn rn//========================= 出错地方rnpublic class PackagMgr : BaseMgrrn rn public static List CURRENT_PACAGE = new List();rn private MyGM myGM_0 = GM.CreateNewGM();rn private ResourceMgr resourceMgr_0 = new ResourceMgr();rn public void Test()rn rn ResourceMgr resourceMgr = new ResourceMgr();rn foreach (ItemDTO current in PackagMgr.CURRENT_PACAGE)rn rn Console.WriteLine(string.Concat(new object[]rn rn current.itemId,rn ":",rn resourceMgr.GetItemByItemID(current.itemId).MyName,rn ":",rn current.itemNum,rn " st:",rn current.storageTypern ));rn rn rnrn public ItemDTO method_0(int id)rn rn ItemDTO result;rnrn for (int i = 0; i < PackagMgr.CURRENT_PACAGE.Count; i++)//出错rn rnrn if (PackagMgr.CURRENT_PACAGE[i].id == id)rn rn result = PackagMgr.CURRENT_PACAGE[i];rn return result;rn rn rnrn result = null;rn return result;rn rnrn public ItemDTO GetItemByItemID(int id)rn rn ItemDTO result;rn for (int i = 0; i < PackagMgr.CURRENT_PACAGE.Count; i++)//出错rn rnrn if (PackagMgr.CURRENT_PACAGE[i].itemId == id)rn rn result = PackagMgr.CURRENT_PACAGE[i];rn return result;rn rnrn rn result = null;rn return result;rnrn//=================调用rnforeach (EquipDTO current in DataCenter.CURRENT_EQUIPS)rn rn string[] array = new string[4];rn ItemDTO itemDTO = packagMgr.method_0(current.id);//调用method_0rnif (itemDTO != null)rnrn Item itemByItemID = resourceMgr.GetItemByItemID(itemDTO.itemId);rn//调用GetItemByItemIDrn if (itemByItemID != null)rn rnrn array[0] = itemByItemID.MyName;rnrn rn rnrn//------调用rnprivate void method_15()rn rn this.util_0.ClearLV(this.lv_seed);rn ResourceMgr resourceMgr = new ResourceMgr();rn List gardenSeed = resourceMgr.GetGardenSeed();rn if (gardenSeed != null && gardenSeed.Count != 0)rn rn List list = new List();rn PackagMgr packagMgr = new PackagMgr();rn foreach (GardenSeed current in gardenSeed)rn rn string[] array = new string[4];rn array[0] = resourceMgr.GetItemNameByItemID(current.SeedID);rn array[1] = current.SeedTime.ToString() + "天";rn array[2] = "0";rnrn ItemDTO itemByItemID = packagMgr.GetItemByItemID(current.SeedID);rn //调用GetItemByItemID rn if (itemByItemID != null)rn rn array[2] = itemByItemID.itemNum.ToString();rn rn array[3] = current.SeedID.ToString();rn list.Add(array);rn[/code]rnrnrnrnrnrnrn[]未处理异常!System.NullReferenceException: 未将对象引用设置到对象的实例。rn 在 Manager.PackagMgr.GetItemByItemID(Int32 id) 位置 E:\工程\PackagMgr.cs:行号 60rn百度好久 发现出现这个问题都是 未初始化 和 NULL值rnpublic static List CURRENT_PACAGE后面加上了new List();rn还是不行rn不知道怎么弄啊 求各位大哥帮帮忙
System.NullReferenceException: 未将对象引用设置到对象的实例!
未将对象引用设置到对象的实例。 rn说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrn执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。 rnrn堆栈跟踪: rnrnrn[NullReferenceException: 未将对象引用设置到对象的实例。]rn HotelOnline.hotelcustomer.index4.InitializeComponent() +84rn HotelOnline.hotelcustomer.index4.OnInit(EventArgs e) +13rn System.Web.UI.Control.InitRecursive(Control namingContainer) +241rn System.Web.UI.Page.ProcessRequestMain() +195rnrn 在本机上运行没问题..但是传到服务器就报错!~~~~这是什么原因啊???
System.NullReferenceException: 未将对象引用设置到对象的实例。!!!
Component1 co=new Component1();rn private void Page_Load(object sender, System.EventArgs e)rn rn rnrn if(!IsPostBack)rn rn bindNew();rn Panel1.Visible=false;rn rn rn void bindNew()rn rn co.adp.Fill(co.ds, "employees");rn DataColumn[] Pmykey = new DataColumn[1]; //宣告新主索引栏位阵列rn Pmykey[0] = co.ds.Employees.EmployeeIDColumn;rn co.ds.Employees.PrimaryKey = Pmykey; //加入主键rn rnAllemployees.DataSource=co.ds.Employees.DefaultView; ==有错!!!rn Allemployees.DataMember="employees";rn Allemployees.DataBind();rn
提示“System.NullReferenceException: 未将对象引用设置到对象的实例。”
<%@ Page language="vb" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="hunjie.ChatRoom.Login" %>rnrn <% rn dim userlist(60)rn dim userlastsaytime(60)rn dim nrn session("usernick")=request.form("username")rn userlist=application("userlist")rn userlastsaytime=application("userlastsaytime")rn for n=1 to 60rn if session("usernick")=userlist(n) and datediff("s",userlastsaytime(n),now)<120 thenrn rn session("errornick")="已经有人使用" & session("usernick") & "昵称了,请更换!"rn response.redirect ("index.aspx")rn response.endrn rn rn end ifrn nextrn %>rnrn为什么提示“System.NullReferenceException: 未将对象引用设置到对象的实例。
COOKIES的System.NullReferenceException: 未将对象引用设置到对象的实例
未将对象引用设置到对象的实例。 rn说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrnrn行 14: protected void Page_Load(object sender, EventArgs e)rn行 15: rn行 16: string ck = Request.Cookies["Ly_Cookies"]["Ly_UserName"].ToString();rn行 17: if (ck == null)rn行 18: rn rnrn源文件: e:\自写.NET\xingerxd\Admin_Index.aspx.cs 行: 16 rnrn堆栈跟踪: rnrnrn[NullReferenceException: 未将对象引用设置到对象的实例。]rn Admin_Index.Page_Load(Object sender, EventArgs e) in e:\自写.NET\xingerxd\Admin_Index.aspx.cs:16rn System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15rn System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34rn System.Web.UI.Control.OnLoad(EventArgs e) +99rn System.Web.UI.Control.LoadRecursive() +47rn System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061rnrn rnrnrnrnrnrn以上是错误的代码rnResponse.Cookies["Ly_Cookies"]["Ly_UserName"] = UserName.Trim();rnResponse.Cookies["Ly_Cookies"]["Ly_UserPurview"] = dr["UserPurview"].ToString();rnrn这个是登录成功后写入的COOKIES,包括用户名和权限rnrn如果是通过登录页面转过去的话,那么就能正常显示rn但是如果是在地址栏里面直接输入需要验证页面的话,比如admin_index.aspxrn那么就会出现错误,错误以上,rn string AdminName = Request.Cookies["Ly_Cookies"]["Ly_UserName"];rnrn这样都有错么,整了我一天的问题了,
System.NullReferenceException: 未将对象引用设置到对象的实例?
未将对象引用设置到对象的实例。 rn说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 rnrn异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。rnrn源错误: rnrnrn行 69: );rn行 70: con.Open();rn行 71: string sql = "select * from [Check] where userName='" + Session["UserName"].ToString() + "'";rn行 72: SqlDataAdapter da = new SqlDataAdapter(sql, con);rn行 73: DataSet ds = new DataSet();rn rnrn源文件: d:\新\Web\0529\userwork\Check.aspx.cs 行: 71 rnrn
System.NullReferenceException: 未将对象引用设置到对象的实例,错误!
OracleConnection oOracleConn = new OracleConnection();rn oOracleConn.ConnectionString ="Data Source=AGENTDB;User Id=agentdba;Password=icbcsg;Integrated Security=no;";rn rn string sqlstr="select distinct BRANCH_NO from gz_users_info "; rn OracleCommand cmd=new OracleCommand(sqlstr,oOracleConn);rn oOracleConn.Open(); rnrn OracleDataReader Ord=cmd.ExecuteReader();rnrn DropDownList ddl=(DropDownList)e.Item.FindControl("DropDownList1");rn ddl.DataSource=Ord;rn ddl.DataValueField="branch_no";rn ddl.DataTextField="branch_no";rn ddl.DataBind();rn Ord.Close();rn oOracleConn.Close();rn上面的代码在ddl.DataSource=Ord;处报System.NullReferenceException: 未将对象引用设置到对象的实例错误,怎么来解决?rn谢谢!rn
相关热词 c++和c#哪个就业率高 c# 批量动态创建控件 c# 模块和程序集的区别 c# gmap 截图 c# 验证码图片生成类 c# 再次尝试 连接失败 c#开发编写规范 c# 压缩图片好麻烦 c#计算数组中的平均值 c#获取路由参数