![](/img/trans.png)
[英]Asp.Net Core - Model Binding For Generic Model Stopped Working After Upgrade To Core 3.0
[英]Model binding stopped working in case of ASP.NET Core 3.1 Web API
我在Startup.cs
中有一个带有以下代码的 ASP.NET Core 3.1 Web API,在这种情况下,模型绑定可以完美运行,没有任何问题:
Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson(newtonsoft =>
{
newtonsoft.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
我做了一个小的更改来封装所有方法并将代码更新为以下内容:发布以下更改模型绑定停止工作。
Startup.cs
:
public virtual void ConfigureServices(IServiceCollection services) => services.AddControllers().Services.AddCustomConfigureOptions();
public static IServiceCollection AddCustomConfigureOptions(this IServiceCollection services) => services.ConfigureOptions<ConfigureJsonOptions>();
ConfigureJsonOptions.cs
:
public class ConfigureJsonOptions : IConfigureOptions<MvcNewtonsoftJsonOptions>
{
private readonly IWebHostEnvironment webHostEnvironment;
public ConfigureJsonOptions(IWebHostEnvironment webHostEnvironment) => this.webHostEnvironment = webHostEnvironment;
public void Configure(MvcNewtonsoftJsonOptions options)
{
if (webHostEnvironment.IsEnvironment(C.Constants.Local))
{
// Pretty print the JSON in development for easier debugging.
options.SerializerSettings.Formatting = Formatting.Indented;
}
// Parse dates as DateTimeOffset values by default. You should prefer using DateTimeOffset over
// DateTime everywhere. Not doing so can cause problems with time-zones.
options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Output enumeration values as strings in JSON.
options.SerializerSettings.Converters.Add(new StringEnumConverter());
}
}
谁能帮我解决这个问题?
那么我注意到的第一件事是你永远不会设置配置类的webHostEnvironment
属性。 问题是,您仍在构建服务定义(请注意,您有IServiceCollection
而不是IServiceProvider
,并且IServiceCollection.ConfigureOptions<TConfigureOptions>()
确实是为了扩展选项模式,这是 IMO 更好地用于服务配置的动态设置.
与其将它封装在一个单独的类中,我会说保持简单并坚持使用基于 lambda 的配置。 如果您必须将其基于环境,请使用类似这样的东西。 如果没有,我总是发现预处理器指令可以非常干净地解决这个问题:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddNewtonsoftJson(jsonSettings =>
{
#if DEBUG
jsonSettings.SerializerSettings.Formatting = Formatting.Indented;
#endif
// Parse dates as DateTimeOffset values by default. You should prefer using DateTimeOffset over
// DateTime everywhere. Not doing so can cause problems with time-zones.
options.SerializerSettings.DateParseHandling =
DateParseHandling.DateTimeOffset;
jsonSettings.SerializerSettings.ReferenceLoopHandling =
ReferenceLoopHandling.Ignore;
// Output enumeration values as strings in JSON.
jsonSettings.SerializerSettings.Converters.Add(new StringEnumConverter());
});
// other service definitions here
// ...
}
这将检查构建是否在调试或发布模式下完成,并且仅在调试构建中包含该行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.