为什么Nancy模型绑定失败?

时间:2015-07-17 20:49:30

标签: nancy

我有一个Nancy.SelfHost服务,对于Get路由工作得很好,但是在Post路由上失败了。如果在以下路由中的Bind< T>()命令失败,并且为该对象定义了无#34; No无参数构造函数"错误:

Post["/schedule"] = _ =>
{
   var schedule = this.Bind<OatiDay[]>();
   PostSchedule(schedule);
   return HttpStatusCode.Created;
};            

以下是返回的错误调用堆栈:

Nancy.RequestExecutionException: Oh noes! ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at Nancy.Serialization.JsonNet.JsonNetBodyDeserializer.CreateObjectWithBlacklistExcluded(BindingContext context, Object deserializedObject)
   at Nancy.Serialization.JsonNet.JsonNetBodyDeserializer.Deserialize(String contentType, Stream bodyStream, BindingContext context)
   at Nancy.ModelBinding.DefaultBinder.DeserializeRequestBody(BindingContext context)
   at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, Object instance, BindingConfig configuration, String[] blackList)
   at Nancy.ModelBinding.DynamicModelBinderAdapter.TryConvert(ConvertBinder binder, Object& result)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at Nancy.ModelBinding.ModuleExtensions.Bind[TModel](INancyModule module)
   at TSID.Scada.Nancy.ScheduleService.<.ctor>b__2(Object _) in p:\TSIDDev\TSID.Scada\TSID.Scada.Nancy\ScheduleService.cs:line 24
   at CallSite.Target(Closure , CallSite , Func`2 , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at Nancy.Routing.Route.<>c__DisplayClass4.<Wrap>b__3(Object parameters, CancellationToken context)
   --- End of inner exception stack trace ---
   at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)

反序列化器看起来好像出了问题,但我无法分辨出正在创建的内容。邮政编码使用Nancy浏览器在服务器上传递所有测试,因此请求必定存在问题。但我无法弄清楚它是什么。 OatiDay类只是一个poco对象。

    public class OatiDay
    {
        [BsonId]
        public string Id { get; set; }
        [BsonDateTimeOptions(DateOnly = true, Kind = DateTimeKind.Local)]
        public DateTime Date { get; set; }
        public String Facility { get; set; }
        public Production OnPeak { get; set; }
        public Production OffPeak { get; set; }

       public class Production
       {
           public Int32 ScheduleForDay { get; set; }
           public double? ActualForDay { get; set; }
           public Int32 ScheduledToDate { get; set; }
           public double? ActualToDate { get; set; }
       }
   }

以下是Angular $ http服务发送的请求:

POST http://buckhorn1:7000/schedule HTTP/1.1
Host: buckhorn1:7000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Referer: http://buckhorn1:7203/schedule
Content-Length: 793
Origin: http://buckhorn1:7203
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

[{"id":"20150712","date":"2015-07-12T00:00:00Z","facility":"Watson","onPeak":{"scheduleForDay":0,"actualForDay":6.56,"scheduledToDate":77,"actualToDate":92.61},"offPeak":{"scheduleForDay":12,"actualForDay":4.26,"scheduledToDate":71,"actualToDate":64.97},"hasPeak":false},{"id":"20150713","date":"2015-07-13T00:00:00Z","facility":"Watson","onPeak":{"scheduleForDay":8,"actualForDay":8,"scheduledToDate":85,"actualToDate":100.61},"offPeak":{"scheduleForDay":4,"actualForDay":4,"scheduledToDate":75,"actualToDate":68.97},"hasPeak":true},{"id":"","date":"2015-07-14T00:00:00.000Z","facility":"Watson","hasPeak":true,"onPeak":{"scheduleForDay":9,"scheduledToDate":94,"actualForDay":9,"actualToDate":109.61},"offPeak":{"scheduleForDay":5,"scheduledToDate":80,"actualForDay":5,"actualToDate":73.97}}]

有谁能告诉我如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

我无法让Nancy模型绑定工作。我怀疑它与骆驼套管体的反序列化有关。我取代了这个:

var schedule = this.Bind<OatiDay[]>();

用这个:

var reader = new StreamReader(this.Request.Body);
string text = reader.ReadToEnd();
var schedule = JsonConvert.DeserializeObject<OatiDay[]>(text);

我的服务正常。

答案 1 :(得分:0)

有同样的问题。这实际上是Newtonsoft.Json问题。

其中一个可以提供帮助:

1)将OatiDay []更改为List。这实际上是我的解决方案。

2)如果可能,添加包含属性的包装类{ OatiDay[] OatiDays { get; set; } }

3)直接Json.Net反序列化(pthalacker回答)

4)实现自定义模型绑定器Nancy.ModelBinding.IModelBinder。