【问题标题】:restsharp unsuccessful postrestsharp 不成功的帖子
【发布时间】:2020-12-03 19:32:43
【问题描述】:

我正在尝试使用 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."

我已经尝试过序列化,但仍然遇到同样的异常。 我做错了什么?

【问题讨论】:

    标签: c# rest restsharp


    【解决方案1】:

    我加了

    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);
    

    【讨论】:

    • 对于未来的访问者:他添加了 request.RequestFormat = DataFormat.Json;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2016-05-18
    • 2014-05-14
    • 2023-01-07
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多