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

ASP.NET Core添加Listproduct路由后Create操作报NullReferenceException

问题

原本直接访问https://localhost:7171/Category/Add时,Create操作可正常运行,但添加Listproduct Action方法后,所有Create操作均抛出NullReferenceException异常,无法访问。Listproduct Action可正常访问,删除该Action后Create操作恢复正常。

Listproduct Action代码

[HttpGet]
[Route("{catname}/{name}")]
public IActionResult Listproduct(string name, string catname)
{
    List<Product> products;
    
    Subcategory subcat = db.Subcategories
                           .Where(x => x.Slug == name && x.Catname == catname)
                           .FirstOrDefault();
    int subid = subcat.SubcatId;

    products = db.Products.ToArray()
                 .Where(x => x.SubcatId == subid).ToList();

    return View(products);
}

Create Action代码

[HttpGet]
public IActionResult Create()
{
    return View();
}
[HttpPost]
public IActionResult Create(CategoryVM model)
{
    if(! ModelState.IsValid)
    {
        return View(model);
    }

    if (db.Categories.Any(x => x.Catname == model.Catname))
    {
        ModelState.AddModelError("", $"{model.Catname} already exists");
        return View(model);
    }


    if (ModelState.IsValid)
    {
        string uniqueFileName = UploadedFile(model);

        var dto = new Category
        {

            Catname = model.Catname,
            Slug = model.Catname.ToLower(),
            Description = model.Description,
            CatImage = uniqueFileName

        };
        db.Categories.Add(dto);

        db.SaveChanges();
    }

    
    TempData["SM"] = $"{model.Catname} category added to list";
    
    return RedirectToAction("Create");
}

错误截图

访问Create操作时的错误

原因与解决方法

核心原因

路由冲突导致访问Create操作时,请求被错误路由到Listproduct方法。ASP.NET Core中属性路由优先级高于约定路由,Listproduct的[Route("{catname}/{name}")]模板会匹配/Category/xxx这类路径(当访问/Category/Create时,catname被赋值为"Create",name为null),此时Listproduct方法中查询不到对应的Subcategory,subcat为null,执行subcat.SubcatId时抛出NullReferenceException。

解决步骤

  1. 修正Listproduct的路由模板,添加明确前缀避免冲突:

    [HttpGet]
    [Route("products/{catname}/{name}")] // 修改为带前缀的路由
    public IActionResult Listproduct(string name, string catname)
    {
        // 原有代码...
    }
    

    这样Listproduct的访问路径变为/Category/products/{catname}/{name},不会和Create的路由混淆。

  2. 为Create Action添加明确属性路由,确保请求正确匹配:

    [HttpGet("Create")] // 若实际用的是"Add"则改为[HttpGet("Add")]
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost("Create")]
    public IActionResult Create(CategoryVM model)
    {
        // 原有代码...
    }
    
  3. 增强Listproduct的空值处理,即使路由误匹配也不会崩溃:

    Subcategory subcat = db.Subcategories
                           .Where(x => x.Slug == name && x.Catname == catname)
                           .FirstOrDefault();
    if (subcat == null)
    {
        return NotFound(); // 返回404或自定义错误视图
    }
    int subid = subcat.SubcatId;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:13:11