builder.Services.AddControllers().AddJsonOptions详细代码
时间: 2024-03-28 16:42:14 浏览: 205
vscode:VSCode的Builder.io-将设计变成代码!
下面是一个使用 AddControllers 和 AddJsonOptions 的 ASP.NET Core 3.1 Web API 的示例代码:
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
namespace MyWebApi
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddDbContext<MyDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("MyDb"));
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
```
这个示例代码中,我们使用了 AddJsonOptions 来设置序列化和反序列化 JSON 数据的行为。其中,我们通过设置 JsonSerializerOptions.PropertyNamingPolicy 和 JsonSerializerOptions.DictionaryKeyPolicy 为 null,来禁用默认的命名策略,这样就可以保留属性和字典键的原始名称。同时,我们也使用了 AddNewtonsoftJson 方法来注册 Newtonsoft.Json 序列化器,并设置其 ContractResolver 属性为 DefaultContractResolver,以便支持更多的序列化选项。
阅读全文