我正在编写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都不受此影响.
如果是这样,我建议您使用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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。