嗯,我也想在全球范围内解决这个问题......并在此过程中扯掉了很多头发。事实证明,WebApi 中没有扩展点,人们希望拦截传入的表单数据并根据需要对其进行修改。那不是很好吗。因此,缺少这些,我尽可能深入地研究 WebApi 源代码,看看我能想出什么。我最终重用了负责解析表单数据的类来创建模型。我只添加了几行来专门处理日期。下面的那个类可以像这样添加到配置中:
private static void PlaceFormatterThatConvertsAllDatesToIsoFormat(HttpConfiguration config)
{
config.Formatters.Remove(
config.Formatters.FirstOrDefault(x => x is JQueryMvcFormUrlEncodedFormatter));
config.Formatters.Add(
new IsoDatesJQueryMvcFormUrlEncodedFormatter());
}
格式化程序:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web.Http.ModelBinding;
namespace WebApi.Should.Allow.You.To.Set.The.Binder.Culture
{
// This class replaces WebApi's JQueryMvcFormUrlEncodedFormatter
// to support JQuery schema on FormURL. The reasong for this is that the
// supplied class was unreliable when parsing dates european style.
// So this is a painful workaround ...
/// <remarks>
/// Using this formatter any string that can be parsed as a date will be formatted using ISO format
/// </remarks>
public class IsoDatesJQueryMvcFormUrlEncodedFormatter : FormUrlEncodedMediaTypeFormatter
{
// we *are* in Israel
private static readonly CultureInfo israeliCulture = new CultureInfo("he-IL");
public override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return true;
}
public override Task<object> ReadFromStreamAsync(Type type
, Stream readStream
, HttpContent content
, IFormatterLogger formatterLogger)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (readStream == null)
{
throw new ArgumentNullException("readStream");
}
// For simple types, defer to base class
if (base.CanReadType(type))
{
return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
}
var result = base.ReadFromStreamAsync(
typeof(FormDataCollection),
readStream,
content,
formatterLogger);
Func<object, object> cultureSafeTask = (state) =>
{
var innterTask = (Task<object>)state;
var formDataCollection = (FormDataCollection)innterTask.Result;
var modifiedCollection = new List<KeyValuePair<string, string>>();
foreach (var item in formDataCollection)
{
DateTime date;
var isDate =
DateTime.TryParse(item.Value,
israeliCulture,
DateTimeStyles.AllowWhiteSpaces,
out date);
if (true == isDate)
{
modifiedCollection.Add(
new KeyValuePair<string, string>(
item.Key,
date.ToString("o")));
}
else
{
modifiedCollection.Add(
new KeyValuePair<string, string>(
item.Key,
item.Value));
}
}
formDataCollection = new FormDataCollection(modifiedCollection);
try
{
return
formDataCollection.ReadAs(type, String.Empty, RequiredMemberSelector, formatterLogger);
}
catch (Exception e)
{
if (formatterLogger == null)
{
throw;
}
formatterLogger.LogError(String.Empty, e);
return GetDefaultValueForType(type);
}
};
return
Task.Factory.StartNew(
cultureSafeTask
, result);
}
}
}