如何在Startup.cs中添加CamelCasePropertyNamesContractResolver?

时间:2014-10-15 22:53:11

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

以下是我Configure课程中的Startup方法。

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();

3 个答案:

答案 0 :(得分:40)

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 UPDATE

MVC现在默认使用驼峰案例名称序列化JSON。看到这个公告。 https://github.com/aspnet/Announcements/issues/194

答案 1 :(得分:23)

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

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

答案 2 :(得分:0)

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