简体   繁体   English

ASP.NET Core 1(RTM)中的自定义DateTime模型绑定器

[英]Custom DateTime model binder in ASP.NET Core 1 (RTM)

I'm writing and ASP.NET Core 1 application, which has a Web API Controller where supplier will post data. 我正在编写ASP.NET Core 1应用程序,它有一个Web API Controller,供应商将发布数据。

This is a simplified version of the Model class to which I will bind the incoming data: 这是Model类的简化版本,我将绑定传入的数据:

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

The problem is that the dates will be posted with German formatting, for instance, 30.09.2016 . 问题是日期将以德语格式发布,例如, 30.09.2016 I do not want to set the global culture of the application to de-DE because a) I'm not German, and b) the rest of the application will work with ISO dates. 我不想将应用程序的全局文化设置为de-DE因为a)我不是德语,b)应用程序的其余部分将使用ISO日期。

I've set to write a custom IModelBinder and, because it's apparently obligatory in ASP.NET Core MVC, an IModelBinderProvider . 我已经开始编写一个自定义的IModelBinder ,因为它在ASP.NET Core MVC中显然是强制性的,一个IModelBinderProvider

Here's my implementation of the IModelBinderProvider : 这是我对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;
    }
}

The problem is that my IModelBinderProvider is only being hit for the Lead class, ie, context.Metadata.ModelType == typeof(Lead) . 问题是我的IModelBinderProvider只被Lead类命中,即context.Metadata.ModelType == typeof(Lead)

I would expect the model binder to see that we're not dealing with a DateTime , move on, and then come back for every property of the Lead class . 我希望模型绑定器看到我们没有处理DateTime ,继续前进, 然后返回Lead类的每个属性
This is apparently not the case, and my custom IModelBinder never get hit. 显然情况并非如此,我的定制IModelBinder永远不会受到打击。

The reason I say that IModelBinderProvider appears to be obligatory no is that I've found no way of directly registering an IModelBinder into the MVC pipeline; 我之所以说IModelBinderProvider似乎是强制性的,是因为我没有办法直接将IModelBinder注册到MVC管道中; I have to register an IModelBinderProvider instead: 必须注册一个IModelBinderProvider:

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

How can I get ASP.NET Core MVC to apply my custom DateTime binder to the Date property of the Lead class? 如何让ASP.NET Core MVC将我的自定义DateTime绑定器应用于Lead类的Date属性? Is there maybe a way to skip the whole IModelBinderProvider business and use just an IModelBinder ? 有没有办法跳过整个IModelBinderProvider业务并只使用IModelBinder

Do you post your values as JSON? 你把你的价值发布为JSON吗? If so, I'd suggest you register a custom JsonConverter with JSON.NET. 如果是这样,我建议您使用JSON.NET注册自定义JsonConverter。 In the converter you'll use a JsonSerializer with a different DateFormatString, in this case a German date format. 在转换器中,您将使用具有不同DateFormatString的JsonSerializer,在本例中为德语日期格式。 All other JsonSerializer aren't affected by this. 所有其他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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asp.net Core 2自定义模型Binder,具有复杂的模型 - asp.net Core 2 Custom Model Binder with complex model Asp.Net Core中用于子类的自定义模型活页夹 - Custom Model Binder In Asp.Net Core for Sub Classes 将自定义模型活页夹应用于asp.net核心中的对象属性 - Apply Custom Model Binder to Object Property in asp.net core 自定义模型绑定器 asp.net core 来绑定字典 - Custom Model binder asp.net core to bind dictionary ASP.NET MVC模型绑定程序无法正确解析ISO DateTime - ASP.NET MVC model binder not parsing ISO DateTime correctly 如何在 ASP.net 核心中为自定义模型绑定器编写单元测试 - How to write unit test for custom model binder in ASP.net core 为 ASP.NET Core 3.1 中的 QueryString 字符串参数自定义 model 绑定器? - Custom model binder for QueryString string parameters in ASP.NET Core 3.1? 如何在ASP.NET Core中使用支持依赖注入的自定义模型绑定器? - How do I use custom model binder that supports dependency injection in ASP.NET Core? 用于抽象模型的Asp.Net Core 2.0(MVC)Content Binder - Asp.Net Core 2.0 (MVC) Content Binder for an abstract model ASP.NET Core MVC 2中抽象类的模型绑定器 - Model binder for abstract class in asp.net core mvc 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM