You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Razor Page更新评论时输入不存在的articleNumber崩溃怎么修复

问题根因

程序崩溃是触发了空引用异常(NullReferenceException),问题出在以下几个环节:

  • 当输入不存在的articleNumber时,FindNewsArticle()方法会返回null,你没有对返回结果做空校验,直接将null赋值给comment.article
  • 后续执行UpdateDb()时,代码访问comment.article.ArticleNumber属性,对null对象取值直接抛出异常导致程序崩溃

另外你代码里还有两处逻辑错误会导致功能异常:

  • SQL语句的WHERE条件书写错误:AND ArticleId = ArticleId属于恒成立条件,会导致只要CommentId匹配就会更新,完全忽略ArticleId的校验,极端情况下会误改全表数据
  • 评论更新成功的提示文案错配,你写的是文章删除的提示

修复方案

1. 新增article查询结果空校验(核心修复崩溃问题)

修改Razor页面后置代码的OnPost方法,在查询文章后立刻判断结果是否为空,为空直接返回错误提示:

public IActionResult OnPost()
{
    if (ModelState.IsValid)
    {
        UserManager findUser = new UserManager();
        comment.user = findUser.FindUser(Convert.ToInt32(HttpContext.Session.GetString("username")));

        NewsArticleManager FindArticleNumber = new NewsArticleManager();
        comment.article = FindArticleNumber.FindNewsArticle(articleNumber);
        // 新增空校验,拦截不存在的articleNumber
        if (comment.article == null)
        {
            ViewData["Message"] = "This article does not exist";
            return Page();
        }

        CommentManager updateToCommentDatabase = new CommentManager();
        bool succeeded = updateToCommentDatabase.UpdateComment(comment);
        if (succeeded)
        {
            // 修正错误的提示文案
            string message = "评论更新成功";
            ViewData["Message"] = message;
        }
        else
        {
            string message = "评论更新失败,请检查评论是否存在";
            ViewData["Message"] = message;
        }
        return Page();
    }
    else
    {
        ViewData["Message"] = "Please enter all data fields";
        return Page();
    }
}

2. 修正SQL语句逻辑错误

修改数据库操作代码的UPDATE语句WHERE条件:

string sql = "UPDATE comment SET CommentId = @CommentId, ArticleId = @ArticleId, UserId = @UserId, CommentText = @CommentText WHERE CommentId = @CommentId AND ArticleId = @ArticleId";

可选优化

给articleNumber绑定属性加数据注解,从前端层面拦截非法输入:

[BindProperty]
[Required(ErrorMessage = "文章编号不能为空")]
[Range(1, int.MaxValue, ErrorMessage = "请输入有效的文章编号")]
public int articleNumber { get; set; }

内容的提问来源于stack exchange,提问作者Jessy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:45:08