首页 / .NET / 正文

[RestSharp].NET/C#程序开发中使用RestSharp模拟发送JSON数据的方法如何实现呢?

4422 发布于: 2018-01-30 读完约需5分钟

问题描述

比如当前需要使用RestSharp模拟发送如下的JSON数据:

{"UserName":"UAT1206252627",
"SecurityQuestion":{
    "Id":"Q03",
    "Answer":"Business",
    "Hint":"The answer is Business"
},
}

JSON数据字符串对应的实体类为:

public class SecurityQuestion
{
    public string id {get; set;}
    public string answer {get; set;}
    public string hint {get; set;}

    public SecurityQuestion(string id)
    {
         this.id = id;
         answer = "Business";
         hint = "The answer is Business";
    }
}

在.NET/C#程序开发中,如何使用RestSharp模拟发送以上JSON数据的请求呢?

方案一

设置请求头headercontent-type:

request.AddHeader("Content-type", "application/json");

使用AddJsonBody(...)方法向RestSharp模拟请求中添加JSON数据:

request.AddJsonBody(
    new 
    {
      UserName = "UAT1206252627", 
      SecurityQuestion = securityQuestion
    });

方案二

实体类:

public class SecurityQuestion
{
    public string Id { get; set; }
    public string Answer { get; set; }
    public string Hint { get; set; }
}

public class RequestObject
{
    public string UserName { get; set; }
    public SecurityQuestion SecurityQuestion { get; set; }
}

RestSharp模拟请求部分:

var yourobject = new RequestObject
            {
                UserName = "UAT1206252627",
                SecurityQuestion = new SecurityQuestion
                {
                    Id = "Q03",
                    Answer = "Business",
                    Hint = "The answer is Business"
                },
            };
var json = request.JsonSerializer.Serialize(yourobject);

request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

IRestResponse response = client.Execute(request);

方案三

RestSharp支持AddObject(...)方法,所以使用:

request.AddObject(securityQuestion);

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

上一篇: [RestSharp].NET/C#程序开发中如何在RestSharp的请求地址中添加GET参数?

下一篇: [RestSharp].NET/C#程序开发中如何使用RestSharp下载并保存文件?

本文永久链接码友网 » [RestSharp].NET/C#程序开发中使用RestSharp模拟发送JSON数据的方法如何实现呢?

分享扩散:

发表评论

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