Similar to this forum post:
https://developer.citrixonline.com/forum/request-not-expected-format
However he didn't really explain what he found was wrong with his code.
I'm using RestSharp to make API calls. I've been able to get it to work great to pull an list of upcoming webinars however when I try to register participant I keep getting a 400/Request not in expected format error.
Following this documentation https://developer.citrixonline.com/api/gotowebinar-rest-api/apimethod/create-registrant, here is my code:
var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/webinars/{1}/registrants", "300000000000xxxxxx", btn.CommandArgument));
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Accept", "application/json");
request.AddHeader("Accept", "application/vnd.citrix.g2wapi-v1.1+json");
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
request.AddParameter("firstName", LoggedInUser.FirstName);
request.AddParameter("lastName", LoggedInUser.LastName);
request.AddParameter("email", LoggedInUser.Email);
var response = client.Execute(request);
var statusCode = response.StatusCode;
Any insights on how I can figure out why I keep getting that error?
Thank you!
Instead of using AddParamter (which adds key/value parameters to the request body), you need to write JSON instead:
request.DataFormat = DataFormat.Json;
request.AddBody(new {
firstName = LoggedInUser.FirstName,
lastName = LoggedInUser.LastName,
email = LoggedInUser.Email
});
You'll also need to clear the handlers (which automatically set the Accept header) if you want to specify them directly:
client.ClearHandlers();
Related
I'm trying to do a POST request in C#, using RestSharp, in Visual Studio 2022.
I tested the API using Postman, which was successful. The API requires a 64-bit encoded Basic Auth (which I have), and a unique API key (which I also have). I then looked at the C# Restsharp code provided by Postman, and tried to copy paste it into my VS project, but most of the libraries were deprecated. I then ended up modifying the code so it didn't give me any errors, and the code itself runs, but getting a semantic error: the request returns "Missing or Malformed URL parameters". In the body parameter, I send one parameter in the form
var body = #"{""fieldNameHere"": intHere}";
My full code (redacted):
var options = new RestClientOptions("URLHERE")
{
Timeout = -1
};
var client = new RestClient(options);
var request = new RestRequest
{
Method = Method.Post
};
request.AddHeader("API_KEY", "keyHere");
request.AddHeader("Authorization", "authHere");
request.AddHeader("Content-Type", "application/json");
var body = #"{""fieldNameHere"": intHere}";
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
RestResponse response = await client.ExecuteAsync(request);
So I tried using a JObject for the parameter, got the same error, this is my code:
JObject jObjectBody = new JObject();
jObjectBody.Add("FieldName", intHere);
request.AddParameter("application/json", jObjectBody, ParameterType.RequestBody);
var clientValue = await client.ExecuteAsync(request);
I also tried using HttpWebRequest, but got an auth error so not sure what was going on there, didn't get that anywhere else. Would prefer to use RestClient anyway. This is the other way I tried to do the body parameter:
string postData = "{\"FieldNameHere\":" + intHere + "}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
I haven't found anything that works yet. If someone can guide me towards a solution I'd be mad grateful, thanks. It definitely seems to be the body giving me the issue.
Ah! For some reason, phrasing my body like this worked:
var body = new { FieldNameHere = intHere }
request.AddJsonBody(body);
I have no idea why this worked, but it did!
A list of things that DID NOT work:
JObject technique
switching header placement
encoding the auth myself
how the RR instantiation is set up
with and without explicitly saying application/json (also including the charset and excluding)
using HttpWebRequest instead of RestSharp
I start using RestSharp library to connect my Windows Forms application with web.
I created a method like this:
public static bool WebRequest(string route, string token, Method method, string model)
{
var client = new RestClient("myapiurl");
var request = new RestRequest(route, method);
//"model" is a json
request.AddParameter("application/json", model, ParameterType.GetOrPost);
request.AddHeader("Accept", "application/json");
request.AddHeader("Authorization", "Bearer " + token);
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
var content = response.Content;
return true;
}
The request has 3 parameters:
{ application/json={ "CommunicationType":4854,"JobNumber":55555,"NotificationAddress":"(714) 978-9788","CreatedBy":"user#mail.com","IsDeleted":false } }
{ Accept=application/json }
{ Authorization=Bearer dasjd... }
But the response always returns:
StatusCode: UnsupportedMediaType
I didn't see anything wrong in my request, can someone see what is wrong?
Regards
Add need to add content type in header
request.AddHeader("content-type", "application/json");
get reference GetOrPost:ParameterTypes for RestRequest
RequestBody If this parameter is set, its value will be sent as the
body of the request. Only one RequestBody parameter is accepted - the
first one.
The name of the parameter will be used as the Content-Type header for
the request.
RequestBody does not work on GET or HEAD Requests, as they do not
actually send a body.
If you have GetOrPost parameters as well, they will overwrite the
RequestBody - RestSharp will not combine them but it will instead
throw the RequestBody parameter away.
It is recommended to use AddJsonBody or AddXmlBody methods instead of
AddParameter with type BodyParameter. Those methods will set the
proper request type and do the serialization work for you.
I think you need to add
request.AddJsonBody(model); // AddJsonBody serializes the object automatically
In case anyone is encountering this, but for GET requests. I was encountering this same error and only saw answers saying a variation of the following solution to fix the Unsupported Media Type issue
request.AddHeader("content-type", "application/json");
For GET requests, you can also encounter this same error if you have the incorrect setting for Accept-Encoding. For my case, the API was only supporting gzip, so it was rejecting the default values that RestSharp was sending for Accept-Encoding header, which was gzip, deflate, br. The solution that worked for me was setting this Rest Client option:
var options = new RestClientOptions(url)
{
AutomaticDecompression = DecompressionMethods.GZip
};
_client = new RestClient(options);
I have a C# REST Web API and I have some code like this that makes a request to an endpoint. Some of the data that I want to pass along is an object of my own type and since it is a complex object, I would like to pass it using POST.
RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint)
{
Timeout = 1000
};
string requestResource = Constants.Endpoints.apiEndPoint;
RestRequest request = new RestRequest(requestResource, Method.POST);
request.AddParameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader);
request.AddHeader("Accept", "application/json");
request.AddParameter("id", id, ParameterType.UrlSegment);
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
On the other side, I am trying to read the object itself with some code like this
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var content in provider.Contents)
{
// what should I do here to read the content as a JSON
// and then transform it as the object it used to be before the call?
}
I tried to do await content.ReadAsJsonAsync< MyType>(); but also tried await content.ReadAsStringAsync(); and none of these worked. Am I doing something wrong at the time I execute in the client? Or is it something that I am doing on the other side while reading the content?
Instead of this line:
request.AddParameter("text/json", objectIWantToSerialize, ParameterType.RequestBody);
You should use the .AddBody(object) method.
So you're code would look like this:
RestRequest request = new RestRequest(requestResource, Method.POST);
//add other headers as needed
request.RequestFormat = DataFormat.Json;
request.AddBody(objectIWantToSerialize);
IRestResponse response = client.Execute(request);
On the server, if you're using MVC/WebAPI, you can just put the C# type as the input and ASP.NET will deserialize it for you. If not, can you provide more context about how you're receiving the request?
Goodmorning everyone,
using postan I make a request as in the figure, and I get data.
I write using the same call (at least I assume) and it returns an empty string and not a json.
Where could it be the mistake?
Thank you all
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY", Method.POST);
// request.RequestFormat = DataFormat.Json;
request.AddParameter("TblName", "STSIG$");
var response = client.Execute(request);
var content = response.Content;
enter image description here
Query Parameter Detail is mentioned in add Parameter. Please change the code as below
Code:
var client = new RestClient("http://pp.miosito.it/API/");
var request = new RestRequest("STHQRY?TblName=STSIG$", Method.POST);
//Request Body detail needs to be added.
//I assumed input is JSON. Please change the header part , if the body has different
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", body, ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content;
I Write one application to access one Webservice Restful using C#, i get the Token with success, i access other services without parameters fine, but when i need to send parameters in POST method it´s not work.
In other side, the Wesbservice dont see my post.
Can someone help-me about this ?
Here is my code.
string urlMethod = metodo;
// "/api/v1/organizacao/criar";
var accessToken = IntegraPb.GetToken();
var client = new RestClient(Sincronizador.Properties.Settings.Default.apiUrl);
var request = new RestRequest(urlMethod, Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", "Bearer " + accessToken);
var jsserie = new System.Web.Script.Serialization.JavaScriptSerializer();
// obj is my class to serialize
request.AddJsonBody(jsserie.Serialize(obj));
IRestResponse response = client.Execute(request);
This image is the request object
AddJsonBody receives a object, not a serialized string of your object. It does the serialization internally.
So use this instead:
request.AddJsonBody(obj);