.NET 6中Halcyon.MVC无法运行,抛出System.TypeLoadException问题求助
Halcyon.MVC 在.NET 6中抛出System.TypeLoadException的解决办法
问题原因
.NET 6(以及对应的ASP.NET Core 6)里,Microsoft.AspNetCore.Mvc.Formatters.JsonSerializerSettingsProvider这个类已经被移除,但Halcyon.MVC的JsonHalOutputFormatter内部还依赖这个已废弃的类型,所以触发了类型加载失败的异常。
解决办法
升级Halcyon.MVC到适配.NET 6的版本
去NuGet检查Halcyon.MVC的最新包,新版本一般会适配ASP.NET Core 6的API变更,替换掉对旧类的依赖。更新包后,原有添加JsonHalOutputFormatter的代码就能正常运行。自定义兼容的Hal JSON输出格式化器(无适配版本时)
如果暂时找不到适配.NET 6的Halcyon版本,可以自己实现一个兼容的格式化器,改用.NET 6默认的System.Text.JsonAPI:using System.Text.Json; using Halcyon.HAL; using Microsoft.AspNetCore.Mvc.Formatters; public class JsonHalOutputFormatterNet6 : TextOutputFormatter { private readonly JsonSerializerOptions _jsonOptions; public JsonHalOutputFormatterNet6(JsonSerializerOptions jsonOptions) { _jsonOptions = jsonOptions; // 添加支持的HAL媒体类型 SupportedMediaTypes.Add("application/hal+json"); SupportedMediaTypes.Add("application/vnd.hal+json"); SupportedMediaTypes.Add("application/vnd.hal.v1+json"); SupportedEncodings.Add(System.Text.Encoding.UTF8); } protected override bool CanWriteType(Type? type) { // 判断是否为HAL Resource类型或其集合 return typeof(Resource).IsAssignableFrom(type) || typeof(IEnumerable<Resource>).IsAssignableFrom(type); } public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { var response = context.HttpContext.Response; var resource = context.Object as Resource; if (resource != null) { await JsonSerializer.SerializeAsync(response.Body, resource, _jsonOptions); } else { var resources = context.Object as IEnumerable<Resource>; if (resources != null) { await JsonSerializer.SerializeAsync(response.Body, resources, _jsonOptions); } } } }之后在Program.cs(或Startup.cs)里注册这个自定义格式化器:
builder.Services.AddControllers(options => { options.OutputFormatters.Add(new JsonHalOutputFormatterNet6(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true // 根据需求调整是否格式化输出 })); });
补充说明
.NET 6开始,ASP.NET Core全面切换到System.Text.Json作为默认JSON处理库,旧的基于Newtonsoft.Json的MVC格式化器相关API(包括JsonSerializerSettingsProvider)都被移除或重构,这是引发该异常的核心原因。
内容的提问来源于stack exchange,提问作者kabilan Mohanasundaram
相关产品推荐
相关产品推荐

