使用C#ASP.NET WebAPI 2.0在InputModel主体中绑定NodeTime即时字段
我有一个WebAPI项目,它在输入模型中接受ISO日期字符串。我一直在使用使用C#ASP.NET WebAPI 2.0在InputModel主体中绑定NodeTime即时字段,c#,json,asp.net-web-api2,model-binding,nodatime,C#,Json,Asp.net Web Api2,Model Binding,Nodatime,我有一个WebAPI项目,它在输入模型中接受ISO日期字符串。我一直在使用DateTimeOffset?解析这些。我想从我的项目中删除BCL datetimes,因此我想找到一种方法,将这些字符串直接绑定到Instant public class MyInputModel { public DateTimeOffset? OldTime { get; set; } public Instant NewTime { get; set; } } 示例JSON输入模型如下所示: {
DateTimeOffset?
解析这些。我想从我的项目中删除BCL datetimes,因此我想找到一种方法,将这些字符串直接绑定到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"
}
var config = new HttpConfiguration();
WebApiConfig.Register(config);
我的控制器代码是:
[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.
}
您应该像这样添加模型活页夹:(在
WebApiConfig
Register
方法中)
WebApiConfig.Register在Startup.cs
文件的Configuration
函数中调用。在大多数情况下,例如:
{
"oldtime":"2016-01-01T12:00:00Z",
"newtime":"2016-01-01T12:00:00Z"
}
var config = new HttpConfiguration();
WebApiConfig.Register(config);
如果未调用,您可以添加以下行:
config.BindParameter(typeof(Instant),new InstantModelBinder())
在
Startup.cs
中创建HttpConfiguration
对象的位置,您注册了什么类型的Type
模型绑定器?嗨,阿拉姆,我还没有注册它-在查询字符串中,我使用它如下:[ModelBinder(BinderType=typeof(InstantModelBinder))]Instant?time=null)
尝试添加这个ModelBinders.Binders.Add(typeof(Instant?),newinstantmodelbinder()代码>在Global.asax.cs
中,或者在MyInputModel
中没有问号,它不可为空。我应该提到-这是一个dotnet ASP.NET WebApi 2.0项目。我们没有使用Global.asax.cs文件。请将其添加到Startup.cs
文件中。在Configuration
中,函数如下:public void Configuration(IAppBuilder app){ModelBinders.Binders.Add(typeof(Instant?),new InstantModelBinder();…}
对不起,我仍然不知道该怎么做。这个方法是由startup类调用的吗?是的,你应该在startup类中有这个方法,或者类似的东西,你只需要HttpConfiguration object
来调用BindParameter
。我有一个Configure
方法,但是没有对HttpConfiguration
的引用,如果我尝试var config=new HttpConfiguration();代码>我找不到它的名称空间-这是一个大项目,但我们没有安装相关的软件包;我觉得这是错误的方法?如果没有创建HttpConfiguration
,您的web api是如何注册的?我可以看看您的Startup.cs
文件吗。