加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:36:08 所属栏目:百科 来源:网络整理
导读:我正在编写ASP.NET Core 1应用程序,它有一个Web API Controller,供应商将发布数据. 这是Model类的简化版本,我将绑定传入的数据: public class Lead{ public int SupplierId { get; set; } public DateTime Date { get; set; }} 问题是日期将以德语格式发布,
我正在编写ASP.NET Core 1应用程序,它有一个Web API Controller,供应商将发布数据.

这是Model类的简化版本,我将绑定传入的数据:

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

问题是日期将以德语格式发布,例如,30.09.2016.我不想将应用程序的全局文化设置为de-DE,因为a)我不是德语,b)应用程序的其余部分将使用ISO日期.

我已经开始编写一个自定义的IModelBinder,因为它在ASP.NET Core MVC中显然是强制性的,一个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;
    }
}

问题是我的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绑定器应用于Lead类的Date属性?
有没有办法跳过整个IModelBinderProvider业务并只使用IModelBinder?

解决方法

你把你的价值发布为JSON吗?
如果是这样,我建议您使用JSON.NET注册自定义JsonConverter.
在转换器中,您将使用具有不同DateFormatString的JsonSerializer,在本例中为德语日期格式.
所有其他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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读