RestSharp simple complete example
I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.
http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/
The blog post is a 2 parter, and the project is here:
https://github.com/dkarzon/DropNet
It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.
Absolutely lost with RestSharp
At https://restsharp.dev/v107/#recommended-usage there is some guidance (but at time of writing this answer I think it might have a typo)
Get docs says:
public class GitHubClient {
readonly RestClient _client;
public GitHubClient() {
_client = new RestClient("https://api.github.com/")
.AddDefaultHeader(KnownHeaders.Accept, "application/vnd.github.v3+json");
}
public Task<GitHubRepo[]> GetRepos()
=> _client.GetAsync<GitHubRepo[]>("users/aspnet/repos");
^^^^^^^^
//note: I think this should be GetJsonAsync
}
Post docs says:
var request = new MyRequest { Data = "foo" };
var response = await _client.PostAsync<MyRequest, MyResponse>(request, cancellationToken);
^^^^^^^^^ ^^^^^^^
//note: i think this should be PostJsonAsync and the first arg should be a string url path
You have classes that represent the json you send/get back, and RestSharp will de/serialize them for you. If you want some help making classes from JSON, take a look at services like http://app.QuickType.io - you paste your json and you get representative classes. The online generators are usually a bit more sophisticated in terms of what they interpret/the attributes they decorate with. Pasting your json into QT gives (you can choose a better name than SomeRoot):
namespace SomeNamespace
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class SomeRoot
{
[JsonProperty("info")]
public Info[] Info { get; set; }
}
public partial class Info
{
[JsonProperty("method")]
public string Method { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
public partial class SomeRoot
{
public static SomeRoot FromJson(string json) => JsonConvert.DeserializeObject<SomeRoot>(json, SomeNamespace.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this SomeRoot self) => JsonConvert.SerializeObject(self, SomeNamespace.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
And use like:
using RestSharp;
using RestSharp.Authenticators;
namespace HttpClientAPP
{
class Program
{
static async Task Main(string[] args)
{
var client = new RestClient("https://data.myhost.de");
client.Authenticator = new HttpBasicAuthenticator("user", "xxxx");
var res = await client.GetJsonAsync<SomeRoot>("");
Console.ReadLine(); //prevent exit
}
}
}
Use POST method in RestSharp
Instead of .AddParameter
you could use AddJsonBody
to get something similar to what Postman sent which you already know works fine.
The code below works for example:
var client = new RestClient("http://api.dastanito.ir");
var request = new RestRequest("/storiesmaster/creat.php", Method.POST);
request.AddJsonBody(new
{
story_code = "value",
master_code = "value2"
});
IRestResponse response = client.Execute(request);
var content = response.Content; // {"message":" created."}
If you inspect the outgoing message with Fiddler, it looks like this:
{"story_code":"value","master_code":"value2"}
Whereas your message using AddParameter
looks like this:
story_code=value&master_code=value2
RestSharp get full URL of a request
To get the full URL use RestClient.BuildUri()
Specifically, in this example use client.BuildUri(request)
:
RestClient client = new RestClient("http://www.some_domain.com");
RestRequest request = new RestRequest("some/resource", Method.GET);
request.AddParameter("some_param_name", "some_param_value", ParameterType.QueryString);
IRestResponse<ResponseData> response = client.Execute<ResponseData>(request);
var fullUrl = client.BuildUri(request);
Related Topics
Starting a Process with Credentials from a Windows Service
ASP.NET MVC 4 C# Httppostedfilebase, How to Store File
How to Get the Local MAChine Name in C#
Why Doesn't Dictionary<Tkey, Tvalue> Support Null Key
Xml Error: There Are Multiple Root Elements
Creating Directories in a Ziparchive C# .Net 4.5
Ternary Operator Vb VS C#: Why Resolves Nothing to Zero
How to Confirm That Mail Has Been Delivered or Not
Task<> Does Not Contain a Definition for 'Getawaiter'
Mixed Mode Assembly Is Built Against Version 'V1.1.4322'
How to Get the Path of the Current User's "Application Data" Folder
C# Array.Findallindexof Which Findall Indexof
How to Bind Datatable to Datagridview in C#