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

ASP.NET MVC AddPet表单提交报405错误及crbug告警问题求解

问题根源

  • 表单默认提交方式为GET,而控制器AddPet方法标记了[HttpPost]仅接收POST请求,请求方法不匹配直接触发405 Method Not Allowed错误。
  • 下拉选单的选项值为字符串,与控制器接收的int类型Pcategory参数不匹配,会导致参数绑定失败。
  • 表单包含文件上传控件但未添加enctype="multipart/form-data"属性,文件无法正常传递到后端,且当前用string类型接收上传文件参数类型错误。
  • crbug/1173575, non-JS module files deprecated.是Chrome浏览器调试的内置警告,和本次405错误无关联,无需处理该提示。

修复步骤

1. 调整视图表单配置

修改表单标签属性,同时修正下拉选单值为数字类型:

<!-- 原<form action="">替换为下面的代码 -->
<form asp-controller="Home" asp-action="AddPet" method="post" enctype="multipart/form-data">

修改下拉选单的option值,和你的分类表实际ID对应即可:

<optgroup label="--Select a Pet Category--">
    <option value="1">Mammls</option>
    <option value="2">Rodents</option>
    <option value="3">Fish</option>
    <option value="4">Reptiles</option>
</optgroup>

2. 调整控制器逻辑

修改参数类型接收上传文件,添加文件保存逻辑,补充数据库提交代码:

[HttpPost]
public IActionResult AddPet(string Pname, int Page, int Pcategory, IFormFile Pimage, string PDescription)
{
    string pictureName = null;
    // 处理图片上传
    if (Pimage != null && Pimage.Length > 0)
    {
        // 生成唯一文件名避免重名
        pictureName = Guid.NewGuid().ToString("N") + Path.GetExtension(Pimage.FileName);
        string saveDir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images");
        // 目录不存在则创建
        if (!Directory.Exists(saveDir))
        {
            Directory.CreateDirectory(saveDir);
        }
        string fullSavePath = Path.Combine(saveDir, pictureName);
        using (var fileStream = new FileStream(fullSavePath, FileMode.Create))
        {
            Pimage.CopyTo(fileStream);
        }
    }

    Animal newAnimal = new Animal()
    {
        Name = Pname,
        Age = Page,
        CategoryID = Pcategory,
        PictureName = pictureName,
        Description = PDescription
    };

    _context.Animals.Add(newAnimal);
    _context.SaveChanges(); // 必须调用该方法才能将数据写入数据库
    
    return View("AddPet");
}

可选优化

你可以直接将Animal作为Action的接收参数,将表单控件的name属性改为和Animal模型的属性名完全一致(比如宠物名称的input name改成Name,年龄改成Age),即可自动完成模型绑定,无需手动逐个声明参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:07