4

我正在尝试使用 restsharp 使用休息服务(wcf)

这是我的服务

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method="POST", UriTemplate = "/PEmploy", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)]
        Employee PostGetEmploy(Employee emp);
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int EmpNo { get; set; }
        [DataMember]
        public string EmpName { get; set; }
        [DataMember]
        public string DeptName { get; set; }
    }

这就是我所说的

    var client = new RestClient("http://localhost:14437/Service.svc");
    var request = new RestRequest("XmlService/PEmploy", Method.POST);
    myRef.Employee emp = new myRef.Employee() { EmpNo = 101, EmpName = "Mahesh", DeptName = "CTD" };
    request.AddParameter("Employee", emp);
    RestResponse<myRef.Employee> response = (RestResponse<myRef.Employee>)client.Execute<myRef.Employee>(request);

这是我得到的例外

    Exception:Caught: "Data at the root level is invalid. Line 1, position 1." (System.Xml.XmlException)
    A System.Xml.XmlException was caught: "Data at the root level is invalid. Line 1, position 1."

我试过序列化,但仍然有同样的异常。我究竟做错了什么?

4

1 回答 1

5

我添加了

request.RequestFormat = DataFormat.Json

这成功了。

完整代码

var client = new RestClient("http://localhost:14437/Service.svc");
var request = new RestRequest("XmlService/PEmploy", Method.POST);
request.RequestFormat = DataFormat.Json;
myRef.Employee emp = new myRef.Employee() { EmpNo = 101, EmpName = "Mahesh", DeptName = "CTD" };
request.AddParameter("Employee", emp);
RestResponse<myRef.Employee> response = (RestResponse<myRef.Employee>)client.Execute<myRef.Employee>(request);
于 2012-09-17T19:45:46.933 回答