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

ASP.NET MVC非PDF文件上传未触发提示,如何修复?

ASP.NET MVC PDF上传功能格式验证问题解决

问题描述

我用ASP.NET MVC开发仅允许上传PDF的功能,控制器代码如下:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase files)
{
    String FileExt = Path.GetExtension(files.FileName).ToUpper();

    if (FileExt == ".PDF")
    {
        Stream str = files.InputStream;
        BinaryReader Br = new BinaryReader(str);
        Byte[] FileDet = Br.ReadBytes((Int32)str.Length);

        FileDetailsModel Fd = new Models.FileDetailsModel();
        Fd.FileName = files.FileName;
        Fd.FileContent = FileDet;

        SaveFileDetails(Fd);

        return RedirectToAction("FileUpload");
    }
    else
    {
        ViewBag.FileStatus = "Invalid file format.";
        return View();
    }
}

选择非PDF文件时,未显示Invalid file format.提示,反而抛出错误:

A public action method 'FileDetails' was not found on controller 'AljawdahNewSite.Controllers.FileUploadController'.

选择PDF文件时可正常保存,需要修改代码实现非PDF文件时显示格式错误提示。

错误原因

else分支执行return View();时,ASP.NET MVC会默认尝试匹配与当前Action同名的视图,若视图路径或命名不符合约定,MVC会误匹配其他视图甚至导向不存在的FileDetails方法,导致报错。此外,代码未校验上传文件是否为空,存在空引用异常风险。

修改方案

1. 明确指定返回的视图名称

强制返回FileUpload视图,避免MVC自动匹配错误:

else
{
    ViewBag.FileStatus = "Invalid file format.";
    return View("FileUpload");
}

2. 增加文件为空的校验逻辑

在方法开头添加判断,防止用户未选文件提交时触发空引用错误:

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase files)
{
    // 校验是否选择了文件
    if (files == null || files.ContentLength == 0)
    {
        ViewBag.FileStatus = "Please select a file to upload.";
        return View("FileUpload");
    }

    String FileExt = Path.GetExtension(files.FileName).ToUpper();

    if (FileExt == ".PDF")
    {
        // 原保存逻辑保持不变
        Stream str = files.InputStream;
        BinaryReader Br = new BinaryReader(str);
        Byte[] FileDet = Br.ReadBytes((Int32)str.Length);

        FileDetailsModel Fd = new Models.FileDetailsModel();
        Fd.FileName = files.FileName;
        Fd.FileContent = FileDet;

        SaveFileDetails(Fd);

        return RedirectToAction("FileUpload");
    }
    else
    {
        ViewBag.FileStatus = "Invalid file format. Only PDF files are allowed.";
        return View("FileUpload");
    }
}

3. 确保视图正确渲染提示信息

在FileUpload.cshtml视图中添加提示显示代码:

@if (!string.IsNullOrEmpty(ViewBag.FileStatus))
{
    <div class="alert alert-danger">@ViewBag.FileStatus</div>
}

修改完成后,上传非PDF文件或未选文件时,页面会正确显示对应的错误提示,避免出现找不到Action的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:23:29