Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

owin - How to add CamelCasePropertyNamesContractResolver in Startup.cs?

Here is my Configure method from my Startup class.

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?}");
    });
}

Where can I access the HttpConfiguration instance, so that I could set the CamelCasePropertyNamesContractResolver, just like I did in WebApi 2:

var formatterSettings = config.Formatters.JsonFormatter.SerializerSettings;
formatterSettings.Formatting = Formatting.None;
formatterSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace services.AddMvc(); with the following.

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

UPDATE

With the current version of ASP.NET, this should do.

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

UPDATE 2

With ASP.NET 5 beta5, which is shipped with Visual Studio 2015 RTM, the following code works

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

UPDATE 3

With ASP.NET 5 beta7, the following code works

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

RC2 UPDATE

MVC now serializes JSON with camel case names by default. See this announcement. https://github.com/aspnet/Announcements/issues/194


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...