出現問題的原因
在Linux環境部署.NET Core程式時,如果要到System.Drawing.Common參考會出現該問題,目前大量的第三方組件使用該Windows專用庫,尤其是涉及圖片處理、Word相關的組件、二維碼等
問題現象
出現相關Gdip例外,安裝相應組件后重啟專案及服務器無效,例外如下
The type initializer for 'Gdip' threw an exception.
at System.Drawing.SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(IntPtr& fontfamily)
at System.Drawing.FontFamily.GetGdipGenericSansSerif()
at System.Drawing.FontFamily.get_GenericSansSerif()
at System.Drawing.Font.CreateFont(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte charSet, Boolean isVertical)
at System.Drawing.Font..ctor(String familyName, Single emSize, FontStyle style, GraphicsUnit unit, Byte gdiCharSet, Boolean gdiVerticalFont)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth)
at OfficeOpenXml.ExcelRangeBase.AutoFitColumns()
at Magicodes.ExporterAndImporter.Excel.Utility.ExportHelper`1.AddHeaderAndStyles()
at Magicodes.ExporterAndImporter.Excel.Utility.ExportHelper`1.Export(ICollection`1 dataItems)
at Magicodes.ExporterAndImporter.Excel.ExcelExporter.ExportAsByteArray[T](ICollection`1 dataItems)
解決辦法
.NET 6之前
在Linux服務器上安裝 libgdiplus 即可解決
libgdiplus是System.Drawing.Common原生端跨平臺實作的主要提供者,是開源mono專案
安裝步驟(以Centos 7為例)
- 更新包
yum install -y epel-release - 查找包
yum whatprovides libgdiplus # 輸出以下內容,具體以顯示為準,注意版本號 # libgdiplus-2.10-10.el7.x86_64 : An Open Source implementation of the GDI+ API. -
- ImageSharp
- SkiaSharp
- Microsoft.Maui.Graphics安裝包
yum install -y libgdiplus-2.10-10.el7.x86_64.NET 6及以后
由于官方不再支持在非Windows環境使用libgdiplus,需要單獨開啟運行時環境支持
處理步驟
- 按照.NET 6之前的方案安裝 libgdiplus
- runtimeconfig.json組態檔中新增
System.Drawing.EnableUnixSupport{ "runtimeOptions": { "configProperties": { "System.Drawing.EnableUnixSupport": true } } }構建專案時,會在輸出目錄中生成[appname].runtimeconfig.json檔案,只需要修改該組態檔即可
其他建議
官方不再建議使用libgdiplus,主要是原因是libgdiplus非常臃腫、外部依賴眾多、未解決bug及例外情況難以修復,修改[appname].runtimeconfig.json只是臨時方案,需要逐步遷移到以下專案
官方參考資料:https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/system-drawing-common-windows-only
感謝您的閱讀,如果您對我的博客所講述的內容有興趣,請繼續關注我的后續博客,我是yswenli ,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/423884.html
標籤:.NET技术
