宁檬檬 2019-04-26 01:40 采纳率: 100%
浏览 823
已采纳

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条回答 默认 最新

  • 1进击的小白 2019-04-26 10:02
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大