我有一个WebAPI项目,它在输入模型中包含ISO日期字符串。我一直使用DateTimeOffset?
解析这些。我想从我的项目中消除BCL日期时间,所以我想找到一种方法将这些字符串直接绑定到Instant
。
public class MyInputModel
{
public DateTimeOffset? OldTime { get; set; }
public Instant NewTime { get; set; }
}
示例JSON输入模型如下所示:
{
"oldtime":"2016-01-01T12:00:00Z",
"newtime":"2016-01-01T12:00:00Z"
}
我的控制器代码是:
[HttpPost]
public async Task<IActionResult> PostTimesAsync([FromBody]MyInputModel input)
{
Instant myOldTime = Instant.FromDateTimeUtc(input.oldTime.Value.UtcDateTime);
Instant myNewTime = input.newTime; // This cannot be used with ISO date strings.
}
我尝试按如下方式构建自定义模型绑定器。 这适用于查询字符串中的模型,但不适用于POST请求正文中的模型。如何将ISO 8601字符串格式的日期输入绑定到NodaTime Instant?
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (!String.IsNullOrWhiteSpace(bindingContext.ModelName) &&
bindingContext.ModelType == typeof(Instant?) &&
bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null)
{
Instant? value;
var val = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName).FirstValue as string;
if (String.IsNullOrWhiteSpace(val))
{
bindingContext.Result = ModelBindingResult.Failed();
return Task.FromResult(0);
}
else if (InstantExtensions.TryParse(val, out value))
{
bindingContext.Result = ModelBindingResult.Success(value);
return Task.FromResult(0);
}
else
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"The date is invalid.");
}
}
bindingContext.Result = ModelBindingResult.Failed();
return Task.FromResult(0);
}
public static bool TryParse(string value, out Instant? result)
{
result = null;
// If this is date-only, add Utc Midnight to the value.
if (value.Length.Equals(10))
{
value += "T00:00:00Z";
}
// Trim milliseconds if present
var decimalPointIndex = value.IndexOf('.');
if (decimalPointIndex > 0)
{
value = value.Substring(0, decimalPointIndex) + "Z";
}
// Attempt to parse
var parseResult = InstantPattern.GeneralPattern.Parse(value);
if (parseResult.Success)
{
result = parseResult.Value;
return true;
}
return false;
}
答案 0 :(得分:1)
您应该像这样添加模型绑定器:(在WebApiConfig
Register
方法中)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.BindParameter(typeof(Instant), new InstantModelBinder())
...
}
}
在Configuration
文件的Startup.cs
函数中调用WebApiConfig.Register。在大多数情况下这样:
var config = new HttpConfiguration();
WebApiConfig.Register(config);
如果没有调用,您只需添加以下行:
config.BindParameter(typeof(Instant), new InstantModelBinder())
在HttpConfiguration
中创建Startup.cs
对象。