0

我有这个常见的 CUser 类

public class CUser
{
    public String Username { get; set; }
    public String Password { get; set; }
}

然后我在使用 RestSharp 的客户端上有这段代码

    public void CreateUser()
    {
        RestRequest request = new RestRequest(Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.Resource = "user/{cUser}";

        CUser user = new CUser
        {
            Username = "Foo",
            Password = "BarBaz"
        };

        request.AddParameter("cUser", user, ParameterType.UrlSegment);

        client.PostAsync<int>(request, (response, handler) =>
            {
                System.Diagnostics.Debug.WriteLine(response.StatusDescription);
                System.Diagnostics.Debug.WriteLine("id: " + response.Data);
            });
    }

而我 global.asax 中的这个 http 路由

            routes.MapHttpRoute(
            name: "CreateUser",
            routeTemplate: "api/{controller}/{cUser}",
            defaults: new
                          {
                              controller = "User",
                              action = "CreateUser",
                              cUser = RouteParameter.Optional
                          });

而这个服务器代码来处理它

    public int CreateUser(CUser cUser)
    {
        User user = new User(cUser);
        LoginManager manager = new LoginManager();
        return manager.CreateUser(user);
    }

但是每次我运行它时,cUser 的值都是空的(用户名和密码),所以我需要做些什么来让它正确地序列化它吗?

4

1 回答 1

3

我认为这就是你想要的:

request.AddParameter("username", user.Username);
request.AddParameter("password", user.Password);

您正在做的事情将导致cUser.ToString(){cUser}占位符取代。

于 2012-05-24T22:23:28.593 回答