号外号外: 原[图享网]更名为 码友网(codedefault.com) 啦,感谢大家一路上的陪伴与支持。代码的世界里,码友网与大家一起同行!

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

.NET 作者: Rector 336阅读 0评论 0收藏 收藏本文

郑重申明:本文未经许可,禁止任何形式转载

问题描述

比如当前需要使用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模拟发送JSON数据的方法如何实现呢?

发布于: 2018-01-30 14:28:21
分享扩散:

文章评论

获取验证码