将对象参数作为JSON对象发送到WCF服务方法时获取空值

时间:2011-11-28 13:02:49

标签: c# wcf json rest

这是我的服务方法签名:

    [OperationContract]
    [System.ServiceModel.Web.WebInvoke(UriTemplate = "/RegisterUser", Method = "POST")]
    void RegisterNewUser(User user);

另外,类型User对其属性上的DataContract属性及其属性上的DataMember属性

以下是我调用服务方法的方法:

 String data = "{\"user\":{\"__type\" : \"User:#PingMe\",\"EmailID\": \"something@something.com\",\"RegistrationID\": \"sdfhjklsdgkdfjgklgdjfklg\"}}";  
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:2443/NotificationService.svc/RegisterUser");
        httpWebRequest.Method = "POST";
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        httpWebRequest.ContentLength = bytes.Length;
        httpWebRequest.ContentType = "text/json; charset=utf-8";
            httpWebRequest.KeepAlive = false;
        Stream requestStream = httpWebRequest.GetRequestStream();
        requestStream.Write(bytes,0,bytes.Length);
        requestStream.Close();


        HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

它成功调用服务方法,但在服务方法的用户参数user.EmailID和User.RegistrationID总是'NULL'

任何想法我在这里缺少什么?

我是否需要将RequestFormat属性设置为WebMessageFormat.JSON?在OperationContract属性?

由于

2 个答案:

答案 0 :(得分:0)

更改此

httpWebRequest.ContentType = "text/json; charset=utf-8";

对此:

httpWebRequest.ContentType = "application/json; charset=utf-8";

和此:

[System.ServiceModel.Web.WebInvoke(UriTemplate = "/RegisterUser", Method = "POST")]

到此:

[System.ServiceModel.Web.WebInvoke(UriTemplate = "/RegisterUser", Method = "POST", BodyStyle=WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]

答案 1 :(得分:0)

在您的服务器中增加MaxpostSize属性 我对IIS没有太多了解,但我认为它对你有用

 <requestLimits maxAllowedContentLength ="<length>" />