DateTime Custom Binder in ASP.NET Core 1 (RTM)

I am writing an ASP.NET Core 1 application that has a web API controller where the provider will send the data.

This is a simplified version of the Model class to which I will bind incoming data:

public class Lead
{
    public int SupplierId { get; set; }
    public DateTime Date { get; set; }
}

The problem is that the date will be published with the German formatting, for example 30.09.2016. I do not want a global application culture de-DE, because a) I am not German, and b) the rest of the application will work with ISO dates.

I decided to write the user IModelBinderand, as it seems, is mandatory in the MVC Core an ASP.NET, IModelBinderProvider.

Here is my implementation IModelBinderProvider:

public class GermanDateTimeModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        if (!context.Metadata.IsComplexType && 
                context.Metadata.ModelType == typeof(DateTime))
            return new GermanDateTimeBinder();

        return null;
    }
}

, IModelBinderProvider Lead, .. context.Metadata.ModelType == typeof(Lead).

, , DateTime, Lead.
, -, , IModelBinder .

, , IModelBinderProvider , - , IModelBinder MVC; , IModelBinderProvider:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(options =>
    {
        options.ModelBinderProviders.Insert(0, new GermanDateTimeModelBinderProvider());
    });
}

ASP.NET Core MVC DateTime Date Lead? , IModelBinderProvider IModelBinder?

+4
1

JSON? , JsonConverter JSON.NET. JsonSerializer DateFormatString, . JsonSerializer .

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
        .AddMvc()
        .AddJsonOptions(option =>
        {
            option.SerializerSettings.Converters.Add(new LeadConverter());
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddDebug();

        app.UseMvcWithDefaultRoute();
    }
}

public class LeadConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new System.NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jsonSerializer = new JsonSerializer
        {
            DateFormatString = "dd.MM.yyyy"
        };

        return jsonSerializer.Deserialize<Lead>(reader);
    }

    public override bool CanConvert(Type objectType) => objectType == typeof(Lead);
}
+1

Source: https://habr.com/ru/post/1656379/


All Articles