使用IFormFile时,在运行时出现此错误:
无法从程序集'Microsoft.AspNetCore.Http,Version = 3.0.0.0,Culture = neutral,PublicKeyToken = adb9793829ddae60'中加载类型'Microsoft.AspNetCore.Http.Internal.FormFile'。
我尝试添加软件包:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.0.0" />
<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.0" />
using Microsoft.AspNetCore.Http.Internal;
IFormFile f = new FormFile(memoryStream, 0, memoryStream.Length, "test", "test.pdf");
存在FormFile Aspnetcore 3.0的文档。但是,当检查我的SDK时,而不是使用3.0。它仅在.net core 2.2中可用。我同时安装了2.2和3.0版本
// C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.dll
#endregion
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http.Internal
{
public class FormFile : IFormFile
}
答案 0 :(得分:6)
我遇到了同样的错误,找不到与该错误直接相关的任何内容,经过两天的努力,终于找到了解决方法。
当您尝试实例化FormFile或FormFileCollection类时,会出现问题。如果该项目没有对Microsoft.AspNetCore.App的框架引用,它将引发以上错误。
解决方案:
无论是哪个实例化FormFile或FormFileCollection类的项目,都需要手动添加Microsoft.AspNetCore.App 框架参考。
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
答案 1 :(得分:0)
我在 .NET 5 下,@RL89 的解决方案在概念上有效,但在实践中它改变了。
您需要将 *.csproj 文件中的第一行更改为:
<Project Sdk="Microsoft.NET.Sdk.Web">
注意它是 Microsoft.NET.Sdk .Web
除非您有 main 方法,否则您的解决方案将无法编译。我只是像这样创建了一个假的 Program.cs
namespace MyClassProjThatTurnedIntoWebProject
{
using System;
public class Program
{
public static void Main(string[] args)
{
throw new NotImplementedException("This project is not meant to be run. https://stackoverflow.com/a/67097605/828184");
}
}
}
然后我可以做一些有趣的事情,比如像这样创建一个新的 FormFile():
FormFile file;
string path = "/file/path.json";
using (var stream = System.IO.File.OpenRead(path))
{
file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}