How to add json to RestSharp POST request
I've ran into this problem as well. Try something like this instead of AddJsonBody
.
request.AddParameter("application/json", locationJSON, ParameterType.RequestBody);
RestSharp POST Object as JSON
There are a couple of issues I can see.
The first is that the object you're sending has no public fields, I'd also simplify the definition a little too:
public class PTList
{
public PTList() { get; set; }
}
The second issue is that you're setting the Content-Type
header which RestSharp will do by setting request.RequestFormat = DataFormat.Json
I'd also be tempted to use generics rather than an Object
Your httpPost method would then become:
protected static IRestResponse httpPost<TBody>(String Uri, TBody Data)
where TBody : class, new
{
var client = new RestClient(baseURL);
client.AddDefaultHeader("X-Authentication", AuthenticationManager.getAuthentication());
var request = new RestRequest(Uri, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(Data);
var response = client.Execute(request);
return response;
}
How to post complex Json data (body) using restsharp?
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;
}
How to send json Data using RestSharp POST Method in c#
in your web api you need to handle the binding json data. WebApi does it by itself normally.
And also you dont have to add header or any parameter with "application/json".
If you could just simply use AddJsonBody(object obj)
method RestSharp will automatically set the header.
Or another way to do that is:
Random r = new Random((int)DateTime.Now.Ticks);
var x = r.Next(100000, 999999);
string s = x.ToString("000000");
string UniqueFileName = "S" + s + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
request.Resource = "api/BFormat/AddNewBFormat";
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
var body = new
{
UploadFileVM = new
{
BordereauxId = "",
BFormatId = "",
FileName = UniqueFileName,
Filesize = 0,
Path = @"c:\sdakdldas\"
}
};
request.AddBody(body); //enter code herE
var queryResult = client.Execute<ResponseData<Guid>>(request).Data;
try
{
Assert.IsTrue(queryResult.ReturnData != null);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
And don't serialize the data by urself. RestSharp will take care of serializing.
Related Topics
How to Format a Number in C# With Commas and Decimals
How to Trigger Event When a Variable'S Value Is Changed
How to Round Up the Time to the Nearest X Minutes
Could Not Start Windows Service, Error 1064
Moq - Non-Overridable Members May Not Be Used in Setup/Verification Expressions
How to Make Blazor Http Get Json Async Request
How to Set Shadow Effect on Imageview
Generate a Zip File from Azure Blob Storage Files
Web API Returning Nested Json Values
Regex to Remove All Special Characters from String
How to Get User Browser Name ( User-Agent ) in ASP.NET Core
How to Combine Values of Several Lists into One in C#
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
Asp.Net Core, Change Default Redirect for Unauthorized
C# Double - Tostring() Formatting With Two Decimal Places But No Rounding
Browser Back Button Navigates to Login Page When User Is Still Logged In