ImageSharp 1.0.0-dev000692加载图片报错:MethodNotFound异常
我来帮你搞定这个问题,你遇到的Method not found: '!0 System.ReadOnlySpan1.get_Item(Int32)'`异常,本质是框架版本和ImageSharp版本不兼容导致的:
核心原因
ImageSharp的1.0.0-dev000692这个开发版本,用到了.NET Core 2.1及以上才引入的ReadOnlySpan<T>相关API特性,但你的项目是基于ASP.NET Core 2.0的,这个旧框架版本根本不支持这些API,所以才会抛出方法找不到的异常。
你的调用代码
byte[] data = GetImage(); var image = Image.Load(data);
完整异常栈信息
Method not found: '!0 System.ReadOnlySpan
1.get_Item(Int32)'. at SixLabors.ImageSharp.Formats.Bmp.BmpImageFormatDetector.IsSupportedFileFormat(ReadOnlySpan1 header)
at SixLabors.ImageSharp.Formats.Bmp.BmpImageFormatDetector.DetectFormat(ReadOnlySpan1 header) at SixLabors.ImageSharp.Image.<>c__DisplayClass0_0.<InternalDetectFormat>b__0(IImageFormatDetector x) at System.Linq.Enumerable.SelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.TryGetLast[TSource](IEnumerable1 source, Func2 predicate, Boolean& found)
at SixLabors.ImageSharp.Image.InternalDetectFormat(Stream stream, Configuration config)
at SixLabors.ImageSharp.Image.Decode[TPixel](Stream stream, Configuration config)
at SixLabors.ImageSharp.Image.WithSeekableStream[T](Stream stream, Func`2 action)
at SixLabors.ImageSharp.Image.Load[TPixel](Configuration config, Stream stream, IImageFormat& format)
at SixLabors.ImageSharp.Image.Load[TPixel](Configuration config, Byte[] data)
at work4all.Server.Api.Core.Controllers.FileController.ResizeBenutzerBild(Byte[] data, Int32 maxHeight, Int32 maxWidth, String filename) in D:\DEV\VSTS-work4all\work4all Server\work4all.Server.Api.Core\work4all.Server.Api.Core\Controllers\FileController.cs:line 211
两个可行的解决方案
1. 升级项目到ASP.NET Core 2.1及以上版本(推荐)
这是最彻底的解决办法:
- .NET Core 2.1+不仅修复了大量旧版本的bug,性能也有显著提升,还能完美适配ImageSharp的新版本
- 后续不会再遇到类似的API兼容问题
升级步骤很简单:
- 打开项目的
.csproj文件,把<TargetFramework>netcoreapp2.0</TargetFramework>改成<TargetFramework>netcoreapp2.1</TargetFramework>(或者更高版本,比如netcoreapp3.1,根据你的需求选择) - 在NuGet包管理器中更新所有相关依赖包,确保它们适配新的框架版本
2. 降级ImageSharp到兼容ASP.NET Core 2.0的版本
如果暂时没法升级框架,那就退一步用旧版ImageSharp:
- 找一个明确支持.NET Core 2.0的ImageSharp版本,比如
1.0.0-beta0007,这个版本是兼容2.0的最后几个测试版之一 - 通过NuGet命令行或者包管理器卸载当前版本,安装指定版本:
Uninstall-Package SixLabors.ImageSharp Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007
小提醒
- 选降级方案的话,后续等项目框架升级后,记得再把ImageSharp更到最新版,享受新特性
- 升级框架前,最好先跑一遍项目的所有测试,确保其他依赖组件不会出问题
内容的提问来源于stack exchange,提问作者slxSlashi

