question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

DateTime format configuration doesn't work for CreateControllersForAppServices controllers

See original GitHub issue

ABP 3.6.1, .net core 2.0

This code runs correctly for common controllers. json is formatted.

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});

But it doesn’t take effect on CreateControllersForAppServices controllers, json result is still like:

2018-05-15T17:26:43.2706968+08:00

and this also doesn’t work:

services.PostConfigure<MvcJsonOptions>(options =>
{
    foreach (var converter in options.SerializerSettings.Converters)
    {
        if (converter is AbpDateTimeConverter timeConverter)
        {
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        }
    }
});

Is there a bug? or what can I do to config the CreateControllersForAppServices controllers’ json format?

thanks.

#3001

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
ismcagdascommented, May 15, 2018

@devsharper could you try it like below;

services.PostConfigure<MvcJsonOptions>(options =>
{
	options.SerializerSettings.ContractResolver = new MyCustomContractResolver();
});

class MyCustomContractResolver : AbpContractResolver
{
	protected override void ModifyProperty(MemberInfo member, JsonProperty property)
	{
		if (property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?))
		{
			return;
		}

		property.Converter = new AbpDateTimeConverter()
		{
			DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
		};
	}
}
0reactions
jifeilong9commented, Nov 29, 2018

@devsharper你可以尝试下面的;

服务。PostConfigure < MvcJsonOptions >(options  =>
{
	选项。SerializerSettings。ContractResolver  =  new  MyCustomContractResolver();
});

class  MyCustomContractResolver:AbpContractResolver
{
	protected  override  void  ModifyProperty(MemberInfo  成员,JsonProperty  属性)
	{
		如果(属性。属性类型 !=  typeof运算(日期时间)&&  属性。属性类型 !=  typeof运算(日期时间?))
		{
			回归 ;
		}

		财产。Converter  =  new  AbpDateTimeConverter()
		{
			DateTimeFormat  =  “ yyyy-MM-dd HH:mm:ss ”
		};
	}
}

@devsharper could you try it like below;

services.PostConfigure<MvcJsonOptions>(options =>
{
	options.SerializerSettings.ContractResolver = new MyCustomContractResolver();
});

class MyCustomContractResolver : AbpContractResolver
{
	protected override void ModifyProperty(MemberInfo member, JsonProperty property)
	{
		if (property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?))
		{
			return;
		}

		property.Converter = new AbpDateTimeConverter()
		{
			DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
		};
	}
}

@devsharper could you try it like below;

services.PostConfigure<MvcJsonOptions>(options =>
{
	options.SerializerSettings.ContractResolver = new MyCustomContractResolver();
});

class MyCustomContractResolver : AbpContractResolver
{
	protected override void ModifyProperty(MemberInfo member, JsonProperty property)
	{
		if (property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?))
		{
			return;
		}

		property.Converter = new AbpDateTimeConverter()
		{
			DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
		};
	}
}

@ismcagdas I used this code swagger login time error (Uncaught TypeError: Cannot read property ‘expireInSeconds’ of undefined at XMLHttpRequest.xhr.onreadystatechange (abp.swagger.js:49))

using System; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Cors.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Castle.Facilities.Logging; using Swashbuckle.AspNetCore.Swagger; using Abp.AspNetCore; using Abp.Castle.Logging.Log4Net; using Abp.Extensions; using HR.BookList.Authentication.JwtBearer; using HR.BookList.Configuration; using HR.BookList.Identity;

using Abp.AspNetCore.SignalR.Hubs; using Microsoft.AspNetCore.Mvc; using Abp.Json; using Newtonsoft.Json.Serialization;

namespace HR.BookList.Web.Host.Startup { public class Startup { private const string _defaultCorsPolicyName = “localhost”;

    private readonly IConfigurationRoot _appConfiguration;

    public Startup(IHostingEnvironment env)
    {
        _appConfiguration = env.GetAppConfiguration();
    }
    class MyCustomContractResolver : AbpContractResolver
    {
        protected override void ModifyProperty(MemberInfo member, JsonProperty property)
        {
            if (property.PropertyType != typeof(DateTime) && property.PropertyType != typeof(DateTime?))
            {
                return;
            }

            property.Converter = new AbpDateTimeConverter()
            {
                DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            };
        }
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
       
        // MVC
        services.AddMvc(
            options => options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName))
        );

        services.PostConfigure<MvcJsonOptions>(options =>
        {
            options.SerializerSettings.ContractResolver = new MyCustomContractResolver();
        });

        IdentityRegistrar.Register(services);
        AuthConfigurer.Configure(services, _appConfiguration);

        services.AddSignalR();

        // Configure CORS for angular2 UI
        services.AddCors(
            options => options.AddPolicy(
                _defaultCorsPolicyName,
                builder => builder
                    .WithOrigins(
                        // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                        _appConfiguration["App:CorsOrigins"]
                            .Split(",", StringSplitOptions.RemoveEmptyEntries)
                            .Select(o => o.RemovePostFix("/"))
                            .ToArray()
                    )
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
            )
        );

        // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new Info { Title = "BookList API", Version = "v1" });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
{
    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = "header",
                Type = "apiKey"
            });
            // Assign scope requirements to operations based on AuthorizeAttribute
            options.OperationFilter<SecurityRequirementsOperationFilter>();
        });
      
        // Configure Abp and Dependency Injection
        return services.AddAbp<BookListWebHostModule>(
            // Configure Log4Net logging
            options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                f => f.UseAbpLog4Net().WithConfig("log4net.config")
            )
        );
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{ app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.

app.UseCors(_defaultCorsPolicyName); // Enable CORS!

app.UseStaticFiles();

app.UseAuthentication();

app.UseAbpRequestLocalization();


app.UseSignalR(routes =>
{
    routes.MapHub<AbpCommonHub>("/signalr");
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "defaultWithArea",
        template: "{area}/{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "BookList API V1");
    options.IndexStream = () => Assembly.GetExecutingAssembly()
        .GetManifestResourceStream("HR.BookList.Web.Host.wwwroot.swagger.ui.index.html");
}); // URL: /swagger

} } }

Read more comments on GitHub >

github_iconTop Results From Across the Web

DateTime format configuration doesn't work for ...
This code runs correctly for common controllers. json is formatted. services.AddControllersWithViews(options => { options.Filters.Add(new ...
Read more >
Developers - DateTime format configuration doesn't work ...
This code runs correctly for common controllers. json is formatted. services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.
Read more >
Trouble with binding DateTime and decimal when using ...
Recently I've migrated project to Core 2.2 and ABP 4.4. Since then I am having troubles with binding DateTime and decimals. It all...
Read more >
Articles Tutorials | AspNet Boilerplate
It is properly integrated and configured to work with the ABP framework. ... To use Mvc datetime format options, you can set this...
Read more >
DateTime not posting correctly to controller
Hello, I have an issue regarding the posting of a DateTimePicker value to a controller. Code is as follows: View: 1.@(Html.Kendo().
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found