Servicestack json客户端post方法没有正确反序列化

时间:2013-03-14 12:59:26

标签: servicestack

当我使用POST时,我遇到了ServiceStack Json客户端无法解析我的结果的问题。 get方法将响应反序列化为UserCredentials对象没有问题,但是当我使用POST方法时,它返回一个具有所有null属性的对象。如果我将传递给Post方法的类型更改为字典,我可以看到它得到了正确的结果,我可以看到其余的调用在Fiddler的http级别成功。

   public UserCredentials Login(string uname, string pwd)
    {
        var url = "/login";
        //note that I have to send a dictionary because if I sent a Login Object with username and password it erronously sends {Login:} in the raw request body instead of {"Uname":uname, "Password":password}

        var login = new Dictionary<string, string>() { { "Uname", uname }, { "Password", pwd } };
        var result = client.Post<UserCredentials>(url, login);

        return result;

    }

这是响应(来自服务器的正确和预期的http响应)

HTTP/1.1 200 OK
Server: nginx
Date: Thu, 14 Mar 2013 12:55:33 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Vary: Accept-Encoding
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Length: 49

{"Uid":1,"Hash":"SomeHash"}

这是UserCredentials类

  public class UserCredentials
  {
    public long Uid;
    public string Hash;
  }

2 个答案:

答案 0 :(得分:1)

您的ServiceStack服务器端代码是什么样的?在服务器上执行类似下面的操作应该允许您像这样使用JsonServiceClient:

致电LoginService:

var client = new JsonServiceClient("http://url.com/login");
var response = client.Post<LoginResponse>(new Login() {Uname = "username", Password = "secret"});
var credentials = response.Credentials;

LoginService实施:

public class Login : IReturn<LoginResponse>
{
    public string Uname { get; set; }
    public string Pasword { get; set; }
}

public class UserCredentials
{
    public long Uid {get; set;}
    public string Hash {get; set;}
}

public class LoginResponse : IHasResponseStatus
{
    public LoginResponse()
    {
        this.ResponseStatus = new ResponseStatus();
    }

    public UserCredentials UserCredentials { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

public class LoginService : Service
{
    public LoginResponse Post(Login request)
    {
        //Code to Get UserCredentials
        return new LoginResponse {UserCredentials = new UserCredentials()};
    }
}

答案 1 :(得分:1)

我认为你只需要创建Uid和Hash公共属性而不是公共字段。但是,如果是这种情况,我不确定您的GET请求如何正确反序列化。

public class UserCredentials
{
    public long Uid {get; set;}
    public string Hash {get; set;}
}