c# - 文件上传时 HttpPostedFileBase 始终为 null,模型绑定(bind)错误

标签 c# asp.net-core-mvc

我正在尝试通过 JQuery Ajax 将文件上传到 ASP.NET Core MVC 应用程序。

HttpPostedFileBase 始终为 null。当我将其作为参数直接放入操作中时,我收到模型绑定(bind)错误。

Javascript:

$(document).on('click', '#attachItemBtn', function () {
    var attachItemFiles = document.getElementById('attachItemFile');

    var formData = new FormData();
    formData.append("Document", attachItemFiles.files[0]);
    formData.append("Id", 1234);
    formData.append("FileName", "test");

    $.ajax({
        cache: false,
        type: "POST",
        data: formData,
        processData: false,
        contentType: 'multipart/form-data',
        url: App.Urls.AddAttachment,
        success: function (data) {
            App.Messages.showErrorMessage('Item attached');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            App.Messages.showErrorMessage('Error Occured While attaching document');
        }
    });

    var debug = 0;
});

行动:

[HttpPost]
public IActionResult AddAttachment(AttachmentItemModel model)
{
    var count = HttpContext.Request.Form.Files.Count;
    int i = 0;
    return Json("done");
}

型号:

public class AttachmentItemModel
{
    public int Id { get; set; }
    public HttpPostedFileBase Document { get; set; }
    public string FileName { get; set; }
}

上述代码适用于HttpContext.Request.Form.Files,但model.Documentnull

当我将操作重写为以下函数签名时,出现错误:

public IActionResult AddAttachment(int Id, string FileName, System.Web.HttpPostedFileBase Document)

然后我收到以下错误:

An unhandled exception occurred while processing the request. InvalidOperationException: Could not create an instance of type 'System.Web.HttpPostedFileBase'. Model bound complex types must not be abstract or value types and must have a parameterless constructor.

我缺少什么?我希望将文件绑定(bind)在我的模型中,而不是使用 HttpContext.Request.Files

最佳答案

你是如何让 HttpPostedFileBase 来解析的?无论如何,它在 ASP.NET Core 中不存在。相反,您应该使用 IFormFile

关于c# - 文件上传时 HttpPostedFileBase 始终为 null,模型绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51952363/

相关文章:

c# - 如何在更改端口 wss 时保留 SSL 的通用名称

c# - 在 C# 中等效于 Java 的 "ByteBuffer.putType()"

c# - 在 ASP.NET Core Mvc 中使用 IDbContextFactory 注册 EF Core

asp.net-core-mvc - SignInManager::ExternalLoginSignInAsync返回IsNotAllowed以进行社交登录

c# - 验证 base64 编码图像 .NET 核心

c# - 需要 JavaScript 语法修正

c# - 为什么foreach循环里面的switch只执行一次

c# - 从 silverlight 应用程序访问 SQL Server 数据库

asp.net-core - .Net Core 图像处理(裁剪和调整大小)/文件处理

c# - 从 ASP.NET Core 1.1 MVC 迁移到 2.0 后自定义 cookie 身份验证不起作用