2

我的 WCF REST-full 服务中有这样的方法

[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 ;
        }

在提琴手中,我确实看到这样的 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 服务可以使用的东西?

4

1 回答 1

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 ;
        }

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

于 2013-10-24T05:34:55.243 回答