Подтвердить что ты не робот

Как добавить CamelCasePropertyNamesContractResolver в Startup.cs?

Вот мой метод 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();
4b9b3361

Ответ 1

Функция Configure была удалена из services.AddMvc() в бета-версии 6 или 7. Для Beta 7 в Startup.cs добавьте следующее в функцию ConfigureServices:

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

Ответ 2

Замените 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

В ASP.NET 5 beta5, который поставляется с RTM для Visual Studio 2015, следующий код работает

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