2

我是 RestSharp 和 WCF 的新手,我正在尝试编写一个工作示例,该示例具有一个 post 方法,该方法将字符串和对象作为参数。我在这里查看了另一个帖子,有人问了同样的问题,但我仍然无法让它工作。有人可以指出我正确的方向。我调试了代码,我得到了一个null对象。这似乎很简单,但我不确定我错过了什么。这就是我到目前为止所拥有的。

服务器端:

[OperationContract]
        [Description("addUser")]
        [WebInvoke(Method = "POST", UriTemplate = "/addUser?id={id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        TSCRUResponse addUser(string id, User usr);


 public TSCRUResponse addUser(string id, User usr)
        {
            TSCRUResponse r = new TSCRUResponse();
            r.status =  id + usr.name + usr.age + usr.gender;
            return r;
        }

上述方法的第一个参数是通过 OK 而不是对象。

这些是对象:

[DataContract]
    public class TSCRUResponse
    {
        [DataMember(Name = "status")]
        public string status { get; set; }
    }

    [DataContract]
    public class User
    {
        [DataMember(Name = "name")]
        public string name { get; set; }
        [DataMember(Name = "age")]
        public string age { get; set; }
        [DataMember(Name = "gender")]
        public string gender { get; set; }
    }

客户端 :

public void postmethod(string uri)
        {
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

            RestClient client = new RestClient();
            client.BaseUrl = "http://localhost:1119/TestService.svc/";
            client.Authenticator = new HttpBasicAuthenticator("username", "password");

            RestRequest request = new RestRequest("addUser?id={id}", Method.POST);
            request.AddHeader("Accept", "application/json");
            request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("id", "12839", ParameterType.UrlSegment);
            User itm = new User { age = "40", name = "user1", gender = "M" };
            request.AddBody(itm);

            var response = client.Execute<TSCRUResponse>(request);
            TSCRUResponse addres = response.Data;
            Console.WriteLine(addres.status);
        }
4

0 回答 0