Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#ASP.NET WebAPI 2.0在InputModel主体中绑定NodeTime即时字段_C#_Json_Asp.net Web Api2_Model Binding_Nodatime - Fatal编程技术网

使用C#ASP.NET WebAPI 2.0在InputModel主体中绑定NodeTime即时字段

使用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输入模型如下所示: {

我有一个WebAPI项目,它在输入模型中接受ISO日期字符串。我一直在使用
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
文件吗。