首页 / .NET / 正文

.NET[C#]RestSharp GET/POST请求如何添加文本参数?

9366 发布于: 2018-01-04 读完约需4分钟

RestSharp GET/POST请求如何添加文本参数?

问题描述

比如当前有一个基于RestSharp封闭的泛型方法,需要在此方法在添加文本参数,如何解决呢?

private T ExecuteRequest<T>(string resource,
                            RestSharp.Method httpMethod,
                            IEnumerable<Parameter> parameters = null,
                            string body = null) where T : new()
{
    RestClient client = new RestClient(this.BaseURL);
    RestRequest req = new RestRequest(resource, httpMethod);

    // Add all parameters (and body, if applicable) to the request
    req.AddParameter("api_key", this.APIKey);
    if (parameters != null)
    {
        foreach (Parameter p in parameters) req.AddParameter(p);
    }

    if (!string.IsNullOrEmpty(body)) req.AddBody(body); // 此处添加 text 文本 作为POST body

    RestResponse<T> resp = client.Execute<T>(req);
    return resp.Data;
}

方案一

req.AddParameter("text/xml", body, ParameterType.RequestBody);

方案二

在RestSharp 105.2.3.0 或者以上版本中,实现代码如下:

request.Parameters.Add(new Parameter() { 
    ContentType = "application/json", 
    Name = "JSONPAYLOAD", // not required 
    Type = ParameterType.RequestBody, 
    Value = jsonBody
});

request.Parameters.Add(new Parameter() { 
    ContentType = "text/xml", 
    Name = "XMLPAYLOAD", // not required 
    Type = ParameterType.RequestBody, 
    Value = xmlBody
});

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [SQL Server]SQL Server中如何只返回日期数据类型的日期部分(Date)

下一篇: .NET[C#]RestSharp GET/POST 等请求中如何使用异步方法 async/await?

本文永久链接码友网 » .NET[C#]RestSharp GET/POST请求如何添加文本参数?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册