我有这样的模特
class MyModel{
public DateTimeOffset plannedStartDate {get;set;}
}
和这样的行动
[HttpPost]
public IActionResult Get(MyModel activityUpdate){
}
我正在发送角度作为json的请求
{
plannedStartDate: 2019-03-04T16:00:00.000Z
}
这是一个有效的日期
但是我在api中得到的是错误的
如果我检查立即窗口中的变量,我可以看到偏移量无法'正确解析qazxsw poi
我试图将mvc选项更改为
这没有帮助,我不认为这是关于反序列化选项。我还有其他编写自定义modelBinder的optiosn吗?
如果您的客户端使用service.AddMvc()
.AddJsonOptions(opt=>
opt.SerializerSettings.DateParseHandling=DateParseHandling.DateTimeOffset);
发送请求,则控制器应指定application/json
以使[FromBody]
能够绑定模型。
JsonInputFormatter
为了启用绑定public IActionResult Get([FromBody]MyModel activityUpdate)
{
//your code.
}
,你可以实现自己的DateTimeOffset
之类的
JsonInputFormatter
在public class DateTimeOffSetJsonInputFormatter : JsonInputFormatter
{
private readonly JsonSerializerSettings _serializerSettings;
public DateTimeOffSetJsonInputFormatter(ILogger logger
, JsonSerializerSettings serializerSettings
, ArrayPool<char> charPool
, ObjectPoolProvider objectPoolProvider
, MvcOptions options
, MvcJsonOptions jsonOptions)
: base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)
{
_serializerSettings = serializerSettings;
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
var request = context.HttpContext.Request;
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync();
var resource = JObject.Parse(content);
var result = JsonConvert.DeserializeObject(resource.ToString(), context.ModelType);
foreach (var property in result.GetType().GetProperties())
{
if (property.PropertyType == typeof(DateTimeOffset))
{
property.SetValue(result, DateTimeOffset.Parse(resource[property.Name].ToString()));
}
}
return await InputFormatterResult.SuccessAsync(result);
}
}
}
注册就好
Startup.cs