2013-05-15 71 views
1

我在WCF应用程序的工作,我调用这个操作JSON解析错误WCF

[ServiceContract] 
public interface IAuditDataService 
{ 

    [OperationContract(Name = "UserAuthentication")] 
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/UserAuthentication?username={username}")] 
    string UserAuthentication(string username, UserData userInfo); 

} 

我收到错误

"Object Reference not set to an instance" 

这里

public string UserAuthentication(string username, UserData userInfo) 
{ 
    string outputData = string.Empty; 
    return userInfo.ToString(); // << Error at this line 
} 

这里是JSON类

[DataContract] 
[Serializable()] 
public class UserData 
{ 
    [DataMember(Name = "UserName", Order = 1)] 
    public string UserName { get; set; } 

    [DataMember(Name = "Password", Order = 2)] 
    public string Password { get; set; } 

    [DataMember(Name = "Token", Order = 3)] 
    public string Token { get; set; } 
} 

这里是通过POST方法JSON请求

{"UserName":"abcd", 
"Password":"1234", 
"Token":"1234"} 

这里是响应截屏enter image description here

任何帮助!

+0

userInfo为空。你从哪里得到这个价值? –

+0

我已编辑它,请检查它。 – Ahmed

回答

4

[WebInvoke]属性的BodyStyle属性指定的样式是WrappedRequest - 这意味着要作为输入传递必须对象中的对象,其成员的名字作为属性名相同的包裹,正如史蒂夫威尔克斯所说。

另一种选择是将BodyStyle更改为Bare;在这种情况下,你的输入应该可以正常工作。换句话说,如果这是您的操作声明,那么您的问题中的输入应该可以工作。

[OperationContract(Name = "UserAuthentication")] 
[WebInvoke(Method = "POST", 
      ResponseFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Bare, 
      UriTemplate = "/UserAuthentication?username={username}")] 
string UserAuthentication(string username, UserData userInfo); 
+0

伟大的你是超人。谢谢 – Ahmed

1

我没有测试过这一点,但你不应该张贴:

{ 
    username: "abcd" 
    userInfo: { 
     "UserName": "abcd", 
     "Password": "1234", 
     "Token": "1234" 
    } 
} 

...?

+3

他正在从请求url获取'username'。检查'UriTemplate'。因此,只有您的解决方案的{{userInfo:{...}}应该这样做。 –

+0

仍然有相同的问题。这是给我错误的请求错误,这是由于“对象引用未设置为实例” – Ahmed

+0

我的不好的用户名 - 感谢指出 - 我懒得滚动:) –