ASP.NET Core MVC集成Blazor组件传模型遇Json循环引用错误
解决ASP.NET Core MVC集成Blazor组件传Model的循环引用错误
问题根源
你配置的Mvc.JsonOptions、Http.Json.JsonOptions等都不生效,是因为Blazor在ServerPrerendered模式下序列化组件参数时,使用的是独立的Razor组件序列化配置,和MVC/API的Json配置不共用。
正确解决方案
1. 配置Razor组件专属的Json序列化选项
在Program.cs(.NET 6+)或Startup.cs(.NET 5及更早)中,针对Razor组件添加Json配置:
.NET 6+ Program.cs示例:
builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddJsonOptions(options => { // 启用循环引用支持 options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve; // 提高最大深度限制 options.JsonSerializerOptions.MaxDepth = 256; });
.NET 5及更早 Startup.cs示例:
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorComponents() .AddServerComponents() .AddJsonOptions(options => { options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve; options.JsonSerializerOptions.MaxDepth = 256; }); }
2. 局部解决:忽略循环引用的导航属性
如果Client类存在循环引用(比如Client包含Order集合,Order又关联回Client),可以直接在不需要序列化的属性上标记[JsonIgnore],避免全局配置:
public class Client { public int Id { get; set; } public string ClientName { get; set; } // 忽略这个会导致循环的导航属性 [JsonIgnore] public ICollection<Order> Orders { get; set; } }
3. 备选:调整组件渲染模式
如果你的Blazor组件不需要交互式功能,可将渲染模式改为Static,此时不需要序列化参数:
<component type="typeof(CompBlazor)" render-mode="Static" param-Client="Model"/>
内容的提问来源于stack exchange,提问作者Nowlights
相关产品推荐
相关产品推荐

