如何在 .net Framework 4.7.2 MVC web app 中使用 .net Standard 2 IFormFile 参考

问题描述 投票:0回答:1

我们正在努力将一些遗留的 .net 框架 4.7.2 网络应用程序转换为 .net 核心。我们正在使用 .net 标准库,以便在我们更新网站之前更新我们的基础设施。因此,我们的域、业务和数据层都是 .net 标准 2,而目前网站是 .net 框架。

在网站中,我们有用户可以上传文件的地方。页面的视图模型以前将这些属性定义为 HttpPostedFileBase,但为了使用 .net 标准,我必须将它们更改为 IFormFile。但是现在,上传文件时出现模型验证错误...

The parameter conversion from type 'System.Web.HttpPostedFileWrapper' to type 'Microsoft.AspNetCore.Http.IFormFile' failed because no type converter can convert between these types.

这是视图模型代码。

public class MarketingDocRequestViewModel
{
       public string CompanyName { get; set; }

       public string FirstName {get;set;}

       public string LastName {get;set;}

       public string Address1 { get; set; }

       public string Address2 { get; set; }

       public string City { get; set; }

       public string State { get; set; }

       public string Zip { get; set; }

       public string Phone { get; set; }

       public string Fax { get; set; }

       public string EmailAddress { get; set; }

       public string Website { get; set; }

       public IFormFile LogoFile { get; set; }
}

我怎样才能让它工作?我找不到将 HttpPostedFileBase 转换为 IFormFile 的方法,也找不到使用流和其他属性更新 IFormFile 实例的方法。

asp.net-core asp.net-mvc-5 .net-standard-2.0 .net-4.7.2
1个回答
-1
投票

我找不到将 HttpPostedFileBase 转换为 IFormFile 和我也找不到新的实例的方法 具有流和其他属性的 IFormFile。

IFormFile 是一个接口而不是类:

您可以尝试实现接口:

public class FormFile : IFormFile
    {
        public FormFile(string filename,byte[] content)
        {
            FileName = filename;
            Content = content;
        }

        private  byte[] Content {  get; set; }

        public string ContentType => throw new NotImplementedException();

        public string ContentDisposition => throw new NotImplementedException();

        public IHeaderDictionary Headers => throw new NotImplementedException();

        public long Length => throw new NotImplementedException();

        public string Name => throw new NotImplementedException();

        public string FileName { get; private set; }

        public void CopyTo(Stream target)
        {
            throw new NotImplementedException();
        }

        public Task CopyToAsync(Stream target, CancellationToken cancellationToken = default)
        {
            throw new NotImplementedException();
        }

        public Stream OpenReadStream()
        {
            throw new NotImplementedException();
        }
    }

在控制器中尝试如下:

 var memorystream = new MemoryStream();
 HttpContext.Request.Files[0].InputStream.CopyToAsync(memorystream);
 var name = HttpContext.Request.Files[0].FileName;
 var content = memorystream.ToArray();

 //create the instance 
 IFormFile formFile = new FormFile(name, content);
© www.soinside.com 2019 - 2024. All rights reserved.