Send JSON date to WCF service

戏子无情 提交于 2019-12-30 05:19:10

问题


I want to post json object to my WCF service

My only problem is his date property. I get the date from an jquery datepicker and i want to get it in my service as c# datetime.

My service:

namespace Employee
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST", 
                   RequestFormat = WebMessageFormat.Json,
                   ResponseFormat = WebMessageFormat.Json,
                   BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool UpdateEmployee(Employee Employee);
    }
}

And this is Employee:

[DataContract]
public class Employee
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Department { get; set; }

    [DataMember]
    public int Salary { get; set; }

    [DataMember]
    public DateTime Hired { get; set; }
}

All the other properties work fine. I just need to convert my date string to json date.


回答1:


The expected format for DateTime object is not the format returned by jQuery's date picker. WCF expects the date in the ASP.NET format (e.g., \/Date(1234567890)\/).

You can use other formats, though, but it's not simple (at least not until .NET 4.0; on 4.5 this got a lot better). Basically, you'd use a string property (which can be private, if your service is running under full trust) which would get the value from the wire, then hook it up to a DateTime property during the serialization episodes. There's more information about this trick at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx, and you can see it on the code below.

namespace StackOverflow_11105856
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
                   RequestFormat = WebMessageFormat.Json,
                   ResponseFormat = WebMessageFormat.Json,
                   BodyStyle = WebMessageBodyStyle.Wrapped)]
        string UpdateEmployee(Employee Employee);
    }

    public class Service : IService1
    {
        public string UpdateEmployee(Employee Employee)
        {
            return string.Format("Name={0},Hired={1}", Employee.Name, Employee.Hired.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Department { get; set; }

        [DataMember]
        public int Salary { get; set; }

        public DateTime Hired { get; set; }

        [DataMember(Name = "Hired")]
        private string HiredForSerialization { get; set; }

        [OnSerializing]
        void OnSerializing(StreamingContext ctx)
        {
            this.HiredForSerialization = this.Hired.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
        }

        [OnDeserializing]
        void OnDeserializing(StreamingContext ctx)
        {
            this.HiredForSerialization = "1900-01-01";
        }

        [OnDeserialized]
        void OnDeserialized(StreamingContext ctx)
        {
            this.Hired = DateTime.ParseExact(this.HiredForSerialization, "MM/dd/yyyy", CultureInfo.InvariantCulture);
        }
    }
}

And the jQuery call:

    function StackOverflow_11105856_Test() {
        var url = "/StackOverflow_11105856.svc/UpdateEmployee";
        var data = {
            Name: "John Doe",
            Department: "Accounting",
            Salary: 50000,
            Hired: $("#StackOverflow_11105856_datepicker").val()
        };
        $.ajax({
            type: 'POST',
            url: url,
            contentType: "application/json",
            data: JSON.stringify({ Employee: data }),
            success: function (result) {
                $("#result").text(result.UpdateEmployeeResult);
            }
        });
    }



回答2:


You should try changing the property BodyStyle = WebMessageBodyStyle.Wrapped to BodyStyle = WebMessageBodyStyle.Bare. This way the framework won't add any extra XML decorations.

Also, you should check the date format coming from the client. Perhaps you should send it from the client in a pre-set format and then have a string property in your object, rather than a DateTime one.

You can add a read-only property which converts the date string to a DateTime, using the already known format.



来源:https://stackoverflow.com/questions/11105856/send-json-date-to-wcf-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!