Reputation: 23
I hope you are doing well !!
I need to do a post request using restsharp, the body to be added to request is given below. This is bit complicated than the post request I have done before.
Complex Post for which I request assistance:
{
"contextInfoId": "string",
"userId": "string",
"specificOs": "string",
"buildPlatform": "string",
"deviceName": "string",
"deviceId": "string",
"token": "string",
"loginInfo": {
"loginInfoId": "string",
"loginDate": "2019-03-14T06:21:39.693Z"
}
}
I have added basic post body to request using below code:
//Add json data/body
request.AddJsonBody(new { buProfileId ="1", divisionNames = "IDC", businessUnitNames = "XYZ", processGroupNames = "ABC", systemOrProjectName = "Test", customername = "User" });
The above C# code work fine for a body like below.
{
"buProfileId": "string",
"divisionNames": "string",
"businessUnitNames": "string",
"processGroupNames": "string",
"systemOrProjectName": "string",
"customername": "string"
}
Could someone please let me know how to achieve the complex post operation.
Upvotes: 1
Views: 1916
Reputation: 2862
You can create an json object and assign your value to it, then you can serialize the json and send in the body
public class LoginInfo
{
public string loginInfoId { get; set; }
public DateTime loginDate { get; set; }
}
public class Context
{
public string contextInfoId { get; set; }
public string userId { get; set; }
public string specificOs { get; set; }
public string buildPlatform { get; set; }
public string deviceName { get; set; }
public string deviceId { get; set; }
public string token { get; set; }
public LoginInfo loginInfo { get; set; }
}
public IRestResponse Post_New_RequestType(string context, string user_ID, string Specific_Os, string Build_Platfrom, string Device_Name, string device_Id, string Token_Value, string login_infoId, DateTime Login_Date)
{
Context tmp = new Context();
tmp.contextInfoId = context;
tmp.userId = user_ID;
tmp.specificOs = Specific_Os;
tmp.buildPlatform = Build_Platfrom;
tmp.deviceName = Device_Name;
tmp.deviceId = device_Id;
tmp.token = Token_Value;
tmp.loginInfo.loginInfoId = login_infoId;
tmp.loginInfo.loginDate = Login_Date;
string json = JsonConvert.SerializeObject(tmp);
var Client = new RestClient(HostUrl);
var request = new RestRequest(Method.POST);
request.Resource = string.Format("/api/example");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = Client.Execute(request);
return response;
}
Upvotes: 1