Angular - WCF RESTful服务 - 发送DateTime

时间:2013-10-24 04:39:13

标签: c# json wcf rest angularjs

我的WCF REST全程服务中有这样的方法

[OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public EventData NewEvent(EventData ev)
        {
            _logger.Info("Save event method called. EventName: " + ev.name);

            return ev;
        }

我正试图从Angular服务中调用它

save: function(event){
            var def = $q.defer();
            $resource('http://localhost/EventRegistration/WebServices/Data.svc/newevent')
                .save(event,
                function(response){def.resolve(response);},
                function(response){def.reject(response)});

            return def.promise ;
        }

在fiddler中我确实看到这样的JSON正在发送到我的WCF方法

{"name":"gfdfg","date":"11/11/2011","time":"3546","location":{"address":"2345","city":"3245","province":"2345"}}

我的服务错误地执行此错误

<p>The server encountered an error processing the request. The exception message is 'There was an error deserializing the object of type EventRegistration.Models.EventData. DateTime content '11/11/2011' does not start with '\/Date(' and end with ')\/' as required for JSON.'. See server logs for more details. The exception stack trace is: </p>
      <p>   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
   at System.ServiceModel.Dispatcher.SingleBodyParameterDataContractMessageFormatter.ReadObject(Message message)

所以,问题是,如何指示Angular将日期时间对象格式化为我的WCF REST服务可以使用的东西?

1 个答案:

答案 0 :(得分:2)

我通过在AngularJS应用程序中向app.js添加这样的方法来解决这个问题

Date.prototype.toMSJSON = function () {
    var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE
    return date;
};

然后在调用我的REST服务之前,我添加了这样一个调用

save: function(event){
            var def = $q.defer();

            event.date = (new Date(event.date)).toMSJSON(); // !!!convert to REST format

            $resource('http://localhost/EventRegistration/WebServices/Data.svc/newevent')
                .save(event,
                function(response){def.resolve(response);},
                function(response){def.reject(response)});

            return def.promise ;
        }

不确定这是否是最佳解决方案,但似乎有效。