【问题标题】:How to add CamelCasePropertyNamesContractResolver in Startup.cs?如何在 Startup.cs 中添加 CamelCasePropertyNamesContractResolver?
【发布时间】:2015-01-21 14:28:29
【问题描述】:

这是我的Startup 类中的Configure 方法。

public void Configure(IApplicationBuilder app)
{
    // Setup configuration sources
    var configuration = new Configuration();
    configuration.AddJsonFile("config.json");
    configuration.AddEnvironmentVariables();

    // Set up application services
    app.UseServices(services =>
    {
        // Add EF services to the services container
        services.AddEntityFramework()
           .AddSqlServer();

        // Configure DbContext
        services.SetupOptions<DbContextOptions>(options =>
        {
           options.UseSqlServer(configuration.Get("Data:DefaultConnection:ConnectionString"));
        });

        // Add Identity services to the services container
        services.AddIdentitySqlServer<ApplicationDbContext, ApplicationUser>()
           .AddAuthentication();

        // Add MVC services to the services container
        services.AddMvc();
    });

    // Enable Browser Link support
    app.UseBrowserLink();

    // Add static files to the request pipeline
    app.UseStaticFiles();

    // Add cookie-based authentication to the request pipeline
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = ClaimsIdentityOptions.DefaultAuthenticationType,
        LoginPath = new PathString("/Account/Login"),
    });

    // Add MVC to the request pipeline
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default", 
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });

        routes.MapRoute(
            name: "api",
            template: "{controller}/{id?}");
    });
}

我在哪里可以访问HttpConfiguration 实例,以便我可以设置CamelCasePropertyNamesContractResolver,就像我在WebApi 2 中所做的那样:

var formatterSettings = config.Formatters.JsonFormatter.SerializerSettings;
formatterSettings.Formatting = Formatting.None;
formatterSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

【问题讨论】:

    标签: owin asp.net-core asp.net-core-mvc


    【解决方案1】:

    services.AddMvc(); 替换为以下内容。

    services.AddMvc().SetupOptions<MvcOptions>(options =>
    {
        int position = options.OutputFormatters.FindIndex(f => 
                                        f.Instance is JsonOutputFormatter);
    
        var settings = new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        var formatter = new JsonOutputFormatter(settings, false);
    
        options.OutputFormatters.Insert(position, formatter);
    });
    

    更新

    对于当前版本的 ASP.NET,应该可以这样做。

    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.OutputFormatters
                   .Where(f => f.Instance is JsonOutputFormatter)
                   .Select(f => f.Instance as JsonOutputFormatter)
                   .First()
                   .SerializerSettings
                   .ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    更新 2

    使用 Visual Studio 2015 RTM 附带的 ASP.NET 5 beta5,以下代码可以工作

    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.OutputFormatters.OfType<JsonOutputFormatter>()
               .First()
               .SerializerSettings
               .ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    更新 3

    使用 ASP.NET 5 beta7,以下代码有效

    services.AddMvc().AddJsonOptions(opt =>
    {
        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });
    

    RC2 更新

    MVC 现在默认使用驼峰式名称序列化 JSON。请参阅此公告。 https://github.com/aspnet/Announcements/issues/194

    【讨论】:

    • 为什么在 ASP.NET 5 中您插入了一个新的格式化程序而不只是更改当前的格式化程序?
    • 那么,您在哪里可以找到这些信息?我在 asp.net 上的文档中找不到它。是否有可以查找的 API 位置?
    【解决方案2】:

    在 Beta 6 或 7 中,Configure 函数已从 services.AddMvc() 中删除。对于 Beta 7,在 Startup.cs 中,将以下内容添加到 ConfigureServices 函数中:

    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.ContractResolver = 
            new CamelCasePropertyNamesContractResolver();
    });
    

    【讨论】:

    • 您还需要添加对Newtonsoft.Json.Serialization 的使用引用。
    【解决方案3】:

    使用以下设置来避免 .net 核心的小写替换 services.AddMvc().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2022-11-29
      • 2015-07-08
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多