Menu
  • HOME
  • TAGS

Returning a simple Guid with RestSharp

c#,restsharp

I guess it's because returning just a GUID isn't valid JSON. It would be returned as a string, and not as a JavaScript object, e.g. { "id": "4bae9421-4fe0-4294-a659-9bc37388344b" }

How to use RestRequest/RestResponse when the web service produces multipart form data in C#?

c#,.net,restsharp

1) how can I execute this request whose response will contain MULTIPART_FORM_DATA? request.AddHeader("Accept", "multipart/form-data") 2) how can I read this response header(contains JSON) using RestClient? See answers to this question. Particularly the third one, which shows how to do it just with .NET 4.5 libraries. You may need to implement...

how do use RESTSHARP send parameter JSON in this formatted JSON sub

c#,.net,json,restsharp

request.AddBody(new { boss = new [] { new { cus="454", date="July23,2015", mangpo="9.1", namo="rattatrayaya"} } }); or you can post direct json object like this... request.AddParameter("application/json; charset=utf-8", "{\"boss\":[{\"cus\":\"454\",\"date\":\"July23,2015\",\"mangpo\":\"9.1\",\"namo\":\"rattatrayaya\"}]}", ParameterType.RequestBody); ...

Dynamically deserializing to a property in RestSharp

c#,restsharp

I suggest you use the XPath equivalent for Json. With Json.NET you can parse the string and create a dynamic object. With SelectToken you can query values, or using Linq. The code looks something like this (I did not test it): // execute the request RestResponse response = client.Execute(request); var...

In C#, can I set some httpclienthandler properties in Restsharp?

c#,rest,restsharp,dotnet-httpclient

You need provide the basic authentication information like below for RestSharp if you want to use the Basic HTTP authentication. _client = new RestClient { BaseUrl =new Uri(myUrl) }; _client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>"); To use the windows authentication: Update: const Method httpMethod = Method.GET; string BASE_URL = "http://localhost:8080/"; var...

What is default timeout value of RestSharp RestClient?

http,timeout,restsharp,rest-client

RestSharp is using HttpWebRequest under the hood, which has a default timeout of 100 seconds.

Post RestSharp Google API Error

json,google-api,restsharp

Thanks to Todd and after some additional digging I found the problem. below is the fixed code: var client = new RestClient("https://www.googleapis.com"); var request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; request.Resource = "youtube/v3/liveBroadcasts?part={part}&key={key}"; request.AddParameter("part", "snippet,status", ParameterType.UrlSegment); request.AddParameter("key", "MyClientId", ParameterType.UrlSegment); request.AddHeader("Authorization", "Bearer " + "MyAccessCode");...

RestSharp: Deserialize Xml to c# Object return null

c#,xml,serialization,restsharp

Finally, it work for me :) public auditypes Execute<auditypes>(RestRequest request) where auditypes : new() { var client = new RestClient(); client.BaseUrl = "https://www.myurl.com/auditypes"; var response = client.Execute<auditypes>(request).Data; return response; } public auditypes GetCall() { var request = new RestRequest(); request.RequestFormat = DataFormat.Xml; return Execute<auditypes>(request); } ...

RestSharp Moq Object Null Exception C# REST Unit Test

c#,rest,nunit,moq,restsharp

Issue has been resolved. I had to uninstall and reinstall Moq with nuget.

How do I wrap a Web Api's async call and results as a synchronous method?

c#,wcf,asp.net-web-api,restsharp

I assume that your WCF service is hosted in ASP.NET. Your problem is here: response.Result. I explain this deadlock situation on my blog. In summary, await will capture the current "context" (in this case, an ASP.NET request context) and will use that to resume the async method. However, the ASP.NET...

Restsharp - Exception due to XElement property

restsharp

RestSharp has no inherent knowledge of XElement, and AddBody will attempt to serialize it like it would any other POCO type - by traversing its properties. You can see this process getting stuck in an infinite cycle quite easily: testObj.FirstNode.Parent.FirstNode.Parent.... Your best bet is to change the type of your...

Converting PHP array of arrays to C#

c#,php,json.net,restsharp

http_build_query($params) produces output that looks like this: user_key=X&client_id=X&label%5B0%5D%5Blanguage%5D=en_US&label%5B0%5D%5Bname%5D=English+label&label%5B1%5D%5Blanguage%5D=fr_CA&label%5B1%5D%5Bname%5D=French+label Which, decoded, looks like: user_key=X&client_id=X&label[0][language]=en_US&label[0][name]=English label&label[1][language]=fr_CA&label[1][name]=French label So, you should be able to do: var request = new RestRequest("/xxx/yyy", Method.POST);...

RestSharp.Portable HttpRequestException 500 (Internal Server Error) on iOS POST Request

ios,web-services,rest,xamarin,restsharp

Opened GitHub issue here for reference: https://github.com/FubarDevelopment/restsharp.portable/issues/31...

Restsharp Not Encoding &s

c#,restsharp

The version of I was using was 105.0.0 which seems to have some encoding issues: https://github.com/restsharp/RestSharp/blob/master/releasenotes.markdown I haven't looked at the source for that but bumping my version to 105.0.1 seemed to fix the issue. Commit with the revert that fixed the encoding issue I encountered....

Problems Deserializing Nested JSON Array in C#

c#,json,json.net,restsharp

The Deserializer expects a JSON Array. Your JSON is a JSON Object containing a JSON Array. There's no way the deserializer can know that you expect it to start its work with the hits array. You need to deserialize as the RootObject. Then you would be able to refer to...

RestSharp Authenticator Follow 302 Redirect

c#,.net,restsharp

Doesn't it always go. You find the solution after you post to stack overflow. https://github.com/restsharp/RestSharp/issues/414 Instead of using an IAuthenticator on the RestClient, I have to build a custom System.Net.IAuthenticationModule. Here is my solution: My RestSharp Authenticator public class MyAuthenticator : IAuthenticator { private readonly CredentialCache _credentials = new CredentialCache();...

Properly format json payload

c#,json,restsharp

I think Dinesh is right, you probably won't get the results you expect by doing it your way. But, to answer your question, the syntax error is because you start a new string with every + operator but you do not prepend with a new @: @"{""supplier"":""" + BeneficiaryName +...

RestSharp removing dot from body

c#,.net,asp.net-web-api2,restsharp

Here is my working example for RestSharp version 105.1.0.0: var message = "VALUE1.VALUE2" var client = new RestClient("http://localhost:64648"); //replace with your domain name var request = new RestRequest("/Home/DoJob", Method.POST); //replace 'Home' with your controller name request.RequestFormat = DataFormat.Json; request.AddBody(new { id = message }); client.Execute(request); And my endpoint definition [HttpPost]...

parse strange JSON response as List

c#,asp.net,json,restsharp

You cant really parse that response to a list it looks more like a dictionary var result = JsonConvert.DeserializeObject<Dictionary<Guid, bool>>(json); var resultlist = result.Select(c => c.Key).ToList(); ...

error getting the api key using restsharp

c#,json,asp.net-web-api,restsharp

If queryResult.Content holds the following json structure: { "ApiKey":"rY88liT/BE98t2e3SLXnCQ==", "UserId":1 } The object you are deserializing to should look like this: public class ApiKeyOjbect { public string ApiKey { get; set; } public string UserId { get; set; } } And an esier way to do it would be to...

Getting error: Method not found: 'Void RestSharp.RestClient.set_BaseUrl(System.String)'. in Twilio-CSharp

c#,dependencies,twilio,restsharp,nopcommerce

Twilio evangelist here. RestSharp made a breaking change in their last release, changing the BaseUrl property from a string to a System.Uri type. The Twilio library was updated to address this change and a new package was released. If you install Twilio package 3.6.25 then it should install RestSharp 105.0.1...

Uploading an IMG file through RestSharp

c#,xamarin,restsharp

Path.GetTempFileName Path.GetTempPath It sounds like you may want to write the file to a temporary file, this would allow you to be in compliance with .AddFile's method signature EDIT // Get an Image instance Image image; using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { image = Image.FromStream(fs); // Save...

RestSharp defaulting Content-Type to application/x-www-form-urlencoded on POST

c#,restsharp

It appears this is a misunderstanding of how RestSharp interprets parameters for post requests. From John Sheehan's post on the google group: If it's a GET request, you can't have a request body and AddParameter adds values to the URL querystring. If it's a POST you can't include a POST...

Http request: Writing binary text file (or image) without headers with filename from content-disposition

c#,node.js,restsharp

You need to use a multipart/form-data parser. For Express, there is multer, multiparty, and formidable. If you want to work with the incoming files as streams instead of always saving them to disk, you could use busboy/connect-busboy (busboy is what powers multer) instead....

Retrieving Freebase topics with RestSharp

c#,.net,json.net,restsharp,freebase

This seems to be an internal deserialization issue with the json deserializer from the RestSharp dll. Using Json.NET, this works perfectly: ...

Using RestSharp to upload an image via Etsy API

c#,image,oauth,restsharp,etsy

I actually just had the exact same problem. I'm using a C# server side handler with RestSharp POSTing a new listing with image data from an HttpPostedFile instance. The draft listings were created just fine, but without any image. Like you mentioned, I saw the tmp_name and errors values which...

ON c# I'm use Restsharp read data json client.Execute(request); why show format XML how do show format JSON

c#,json,xml,restsharp

The request executes correctly but the server returns XML instead of JSON. It is not a client-side error. Most probably, the reason is that the server doesn't know the format of expected response and XML is default. It's up to your server's settings. Maybe, he always returns data in XML....

Read response header using RestSharp API in C#

c#,json,.net-4.0,restsharp

Figured out a way to do it and it's working fine. response.Headers.ElementAt(i).Name.ToString(); response.Headers.ElementAt(i).Value.ToString(); ...

How do I just get a list of JSON objects from RestSharp?

c#,json,restsharp

If you really just need the three strings, then deserialize it as a list of dictionaries then use Linq to pick out the values: var serializer = new RestSharp.Deserializers.JsonDeserializer(); var list = serializer.Deserialize<List<Dictionary<string, string>>>(json).SelectMany(d => d.Values).ToList(); ...

System.Net.WebException not intercepted on Windows Phone 8

c#,windows-phone-8,restsharp

Reason is that exceptions from an Async Void Method Can’t Be Caught with Catch. "Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there...

RestRequest and Square Connect

c#,restsharp,square-connect

I cannot try this currently, so I'm not sure it will be the fix you are looking for, but it's just a thought: try to initialize the RestClient with the Uri string, and the RestRequest with the rest of the string, or with empty string, like this: var client =...

RestSharp - How do I get the numerical http response code?

c#,http,restsharp

Simply grab the ResponseCode property off of the RestResponse object and cast the enum value to int. RestResponse response = client.Execute(request); HttpStatusCode statusCode = response.StatusCode; int numericStatusCode = (int)statusCode; ...

RestSharp Serialize/Deserialize Naming Conversion

c#,json,serialization,restsharp,plivo

Unfortunately it looks as though JSON property renaming is not implemented out of the box in RestSharp. You have a couple of options: Download Restsharp from https://github.com/restsharp/RestSharp and rebuild it yourself enabling the compiler option SIMPLE_JSON_DATACONTRACT. Then you will be able to rename properties using data contract attributes. For more,...

Unit testing MassTransit consumers that make utilize asynchronous calls

c#,asynchronous,async-await,restsharp,masstransit

Honestly, the complexity of doing asynchronous methods is one of the key drivers of MassTransit 3. While it isn't ready yet, it makes asynchronous method invocation from consumers so much better. What you're testing above, because you are calling ExecuteAsync() on your REST client, and not waiting for the response...

Restsharp- Method.POST is not working

web-api,restsharp

Get it resolved myself, sharing so others can get benefited: Just need to do the request as: request.AddParameter("Application/Json", myObject, ParameterType.RequestBody); So, complete snippet looks like: public void SomeAPIRequest() { var baseUrl = "someurl from config"; var client = new RestClient(baseUrl); var request = new RestRequest("/api/saverperson/{name}/{fathername}",Method.POST); request.RequestFormat = DataFormat.Json; request.AddParameter("Application/Json", myObject,...

Deserialize JSON into Models that render in partial view (restsharp or any other method)

c#,json,asp.net-mvc,restsharp

RestSharp can do this for you automatically: public ActionResult GetImageOffer(string oid, string otr) { var client = new RestClient("valid url"); var request = new RestRequest("/Offer/OfferDirect", Method.POST); request.AddQueryParameter("oid", oid); request.AddQueryParameter("otr", otr); request.AddHeader("apikey", "secretkeyhere"); request.RequestFormat = DataFormat.Json; RestResponse<RootObject> response = client.Execute<RootObject>(request); return PartialView("_pImageOfferModel", response.Data); } ...

RestSharp calling WebAPI with Thinktecture AuthenticationConfiguration

asp.net-mvc,asp.net-web-api,asp.net-web-api2,restsharp,thinktecture-ident-model

Looks like your JavaScript code and RestSharp request code doesn't match. In JS you set a header with name Authorization and give it a value Session sometoken: xhr.setRequestHeader("Authorization", "Session " + authToken); In RestSharp you assign a header with name Authorization a value Authorization Session sometoken request.AddHeader(authHeader, string.Format("Authorization Session {0}",...

Getting async await and task working

c#,asynchronous,monotouch,async-await,restsharp

What we can do is wrap RestClient.ExecuteAsync<T> inside a method which returns a Task<T> and is implemented using the Task Asynchronous Pattern with the help of a TaskCompletionSource First, lets wrap the ExecuteAsync<T> call inside the TestAPI class: class TestAPI { APIClient API; public TestAPI(APIClient APIClient) { this.API = APIClient;...

using JSON response from REST api with nonstandard names

c#,json,rest,restsharp

String.replace() balances-and-info with balances_and_info in your code YourObject deserialized = parseResponse(obj.replace("balances-and-info", "balances_and_info")); YourObject parseResponse(string response) { try { // https://www.nuget.org/packages/Newtonsoft.Json/ // Json.NET YourObject ret = JsonConvert.DeserializeObject<YourObject>(response); return ret; } catch (JsonSerializationException) { // do something } return null; } YourObject Use http://json2csharp.com/ and generate your object (copy response string, replace...

How to implement call to call ExecuteAsync using RestSharp

c#,restsharp

There are a few ways to implement what you're trying to do, but the it looks like your callback has wrong method signature...to get something "basic" running, the following should work (I added wait simply for testing): EventWaitHandle resetEvent = new AutoResetEvent(false); client.ExecuteAsync(request, response => { callback(response.Content); resetEvent.Set(); return; });...

RestSharp Deserialization not working

c#,deserialization,restsharp

I really don't know why I am providing you with this answer. But still, I am. You should go and get Json.NET via NuGet and let it help you out. It's more sophisticated than RestSharp's built-in de/serialization. Once you have Json.NET, then your JSON can be de/serialized using the classes...

Windows phone 8 RestSharp request. Async/await

c#,rest,windows-phone-8,async-await,restsharp

You're calling an async method without awaiting it inside the constructor. That's why "it doesn't wait" (because it has nothing to wait on). It's usually a bad idea to call an async method inside the constructor for that reason combined with the fact that constructors can't be async. You should...

How to solve UnsupportedMediatType when using RestSharp and OAuth2

c#,rest,oauth-2.0,restsharp

Look at what you're doing here request.AddParameter("application/json", String.Format( "{{\"email\": \"{0}\", \"key\": \"{1}\"}}", email, key ), ParameterType.RequestBody); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("access_token",APIAuthenticator.Instance().GetAccessToken(proxy)); First you set the body to your JSON with the application/json Content-Type. A request can only have one body. What you are doing with the last two lines is overriding the...

Deserialize JSON with dynamic objects

c#,json,restsharp

Since this JSON is not C# friendly, I had to do a little bit of hackery to make it come out properly. However, the result is quite nice. var json = JsonConvert.DeserializeObject<dynamic>(sampleJson); var data = ((JObject)json.data).Children(); var stuff = data.Select(x => new { AreaCode = x.Path.Split('.')[1], City = x.First()["city"], State...