using Rest client and getting statuscode 406 not acceptable - c#

I'm using RestClient and redirecting the request to external REST webservice (java) as RestRequest. I'm getting HTTP statuscode 'not acceptable' and also the repsonse.content is something like this "The resource cannot be displayed because the file extension is not being accepted by your browser."
the operation is successful but not able to get the required response which is nothing but a string value.
below is code snippet:
var client = new RestClient();
client.BaseUrl = JavaWSURI;
var request = new RestRequest();
//request.AddHeader("Content-Length", int.MaxValue.ToString());
//request.AddHeader("Content-Type", "text/html; charset=utf-8");
// jsonD is JSON input object
request.AddParameter("application/json", jsonD, ParameterType.RequestBody);
request.Method = Method.POST;
request.RequestFormat = DataFormat.Json;
// The server's Rest method will probably return something
var response = client.Execute(request) as RestResponse;

From the error message, it sounds like you may need to add an 'Accept' header to the request

Add an Accept request header as follows:
request.AddHeader("Accept",
"text/html, application/xhtml+xml, application/xml;q=0.9, image/webp, */*;q=0.8");
Please note you may need to change the value depending on your content.

Related

Unsupported media type using RestSharp library

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);

C# winform send request content type application/x-www-form-urlencoded with Restsharp

I am developing an small app with C# window form.
I can use Restsharp to send any request with content type application/json. But with application/x-www-form-urlencoded the server always return nothing or Internal error.
I have tested this api with Postman and Restlet Client and it work well.
Following some example on internet but it not work too.
Here is my code:
var client = new RestClient("http://www.nhimanhma.com");
var request = new RestRequest("users/sign_in", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
string formData = $"token={token}&user[email]={email}&user[password]={password}";
string urlEncode = RestSharp.Extensions.StringExtensions.UrlEncode(formData);
request.AddParameter("application/x-www-form-urlencoded", urlEncode, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;

send Header and Request in post method

I am trying to send Header and Request in post method using RestClient library but getting error:
Endpoint not found.
var client = new RestClient("http://xxxxxxxxxx/UIService.svc/xxxxxxxxx/xxxxx");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Authentication", jsonHeadEncrpt);
// request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", JsonReqEncrpt, ParameterType.RequestBody);
var responsed = client.Execute(request);
Response :Endpoint not found. Please see the service help page for constructing valid requests to the service
Guys Found the solution need to add request.Resource where need to assign the endpoint function..Now it is working fine

Use RestSharp Post Object as JSON and read it from the other side of the call

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?

Docusign /oauth/token endpoint return page instead of json with bearer C#

I went through the OAuth2 proccess in DocuSign API, I follow all the steps using official docs, but when I tried to perform the request in order to get the the AccessToken I received an HTML as response, indicating something like "DocuSign is temporarily unavailable. Please try again momentarily." Although the http response is 200(OK), The weird stuff is when I test with the same values on Postman I get the correct response.
This is my code
public static DocuSignBearerToken GetBearerToken(string AccessCode, bool RefreshToken = false)
{
string AuthHeader = string.Format("{0}:{1}", DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var client = new RestClient("http://account-d.docusign.com");
client.Authenticator = new HttpBasicAuthenticator(DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var request = new RestRequest("/oauth/token", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("authorization", "Basic " + Base64Encode(AuthHeader));
if(!RefreshToken)
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=authorization_code&code={0}", AccessCode), ParameterType.RequestBody);
else
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=refresh_token&refresh_token={0}", AccessCode), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseString = response.Content;
DocuSignBearerToken Result = JsonConvert.DeserializeObject<DocuSignBearerToken>(responseString);
return Result;
}
Ok, this is awkward, reading the DocuSign docs they never specify if the authorization URL is http or https I assumed it was http, postman is smart enough to determine http or https when performs the request, my code doesn't, simply changing the Authorization URL from http:// to https:// solves the error.
If your tests using Postman work, then there is a problem with your code.
We've all been there, including me!
In these cases, I send my request to requestb.in to see what I'm really sending to the server. You'll find something is different from what you're sending via Postman.

Categories