【问题标题】:Read RestSharp response and save data to class读取 RestSharp 响应并将数据保存到类
【发布时间】:2021-10-29 02:45:45
【问题描述】:

我发送一个 RestRequest 并接收 xml 格式的响应。 这是我的代码:

class Employee 
{
    int id;
    string name;
}
private void reqEmployee(Employee empl)
{
    var client = new RestClient(ConfigurationManager.AppSettings["base_url"] + "/" +
                                ConfigurationManager.AppSettings["provider"] + "/" +
                                ConfigurationManager.AppSettings["serviceName"])
    {
        Timeout = -1
    };

    var request = new RestRequest(Method.POST);

    var authenticationString = string.Format("{0}:{1}", ConfigurationManager.AppSettings["serviceUser"], ConfigurationManager.AppSettings["servicePass"]);
    var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));

    request.AddHeader("Authorization", "Basic " + base64EncodedAuthenticationString);
    request.AddHeader("Content-Type", "text/plain");

    var body = @"<GetEmployee xmlns=""http://test.dev.com/"">"
                + "\n" + @"    <Id>" + empl.idno + "</Id>"
                + "\n" + @"</GetEmployee>";


    request.AddParameter("text/plain", body, ParameterType.RequestBody);

    IRestResponse response = client.Execute(request);
}

我发送的请求示例:

<GetEmployee xmlns="http://test.dev.com/">
    <Id>4132</Id>   
</GetEmployee>

我收到的回复示例 (response.Content):

<GetEmployeeResponse xmlns="http://test.dev.com/">
    <PropertyStatus xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <Employee>
            <Name>John</Name>
            <Id>6584</Id>
        </Employee>
        <Employee>
            <Name>Chris</Name>
            <Id>4120</Id>
        </Employee>
    </PropertyStatus>
</GetEmployeeResponse>

如何用response.Content 填写List&lt;Employee&gt;

【问题讨论】:

  • 这能回答你的问题吗? Building XML request with RestSharp
  • 谢谢你的回答,这个链接是关于发送一个包含对象数组的请求,我只想读取响应并将其保存为员工数组
  • 如果您在请求中设置了 DataFormat 和 Serializer,那么您可以调用 Execute&lt;T&gt;,您可以在其中指定 List&lt;Employee&gt; 作为预期输出。
  • 这里是another SO thread,其中详细介绍了这个概念。

标签: c# xml rest restsharp


【解决方案1】:

你只需要:

  • 配置默认的 XML 序列化程序
  • 准备您的 POCO 类,以便使用序列化属性进行序列化
  • 使用 RestSharp 客户端通用 Execute&lt;T&gt;

https://restsharp.dev/usage/serialization.html#default-serializers

https://restsharp.dev/getting-started/getting-started.html#content-type

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 2017-10-17
    • 2022-12-12
    • 2021-09-20
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    相关资源
    最近更新 更多