使用C#ASP.NET WebAPI 2.0在InputModel主体中绑定NodaTime Instant字段
本文关键字:主体 绑定 NodaTime 字段 Instant InputModel NET C#ASP WebAPI 使用 | 更新日期: 2023-09-27 17:59:23
我有一个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;
}
您应该这样添加模型绑定器:(在WebApiConfig
Register
方法中)
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.BindParameter(typeof(Instant), new InstantModelBinder())
...
}
}
WebApiConfig.Register是在Startup.cs
文件中的Configuration
函数中调用的。在大多数这样的情况下:
var config = new HttpConfiguration();
WebApiConfig.Register(config);
如果没有调用,您可以添加以下行:
config.BindParameter(typeof(Instant), new InstantModelBinder())
其中CCD_ 8对象正在CCD_。