jgiacomini / tiny.restclient Goto Github PK
View Code? Open in Web Editor NEWSimpliest Fluent REST client for .NET
License: MIT License
Simpliest Fluent REST client for .NET
License: MIT License
I suggest you a feature to add properties in a form by passing a class.
this can also be used for querystring and multipart stringcontent
public IFormRequest AddFormParameters<TParameters>(TParameters parameters)
where TParameters : class
{
if (_formParameters == null)
{
_formParameters = new List<KeyValuePair<string, string>>();
_content = new FormParametersContent(_formParameters, null);
}
foreach (var property in typeof(TParameters).GetProperties())
{
var getValue = property.GetValue(parameters);
string value = null;
if (getValue != null)
{
if (IsGenericList(property.PropertyType))
{
var values = (IEnumerable)getValue;
value = string.Join(",", values.OfType<object>());
}
else if (property.PropertyType == typeof(DateTime)
|| property.PropertyType == typeof(DateTime?))
{
value = ((DateTime)getValue).ToString("s");
}
else
{
value = getValue.ToString();
}
}
if (!string.IsNullOrEmpty(value))
{
_formParameters.Add(new KeyValuePair<string, string>(property.Name, value));
}
}
return this;
}
public static bool IsGenericList(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsGenericType)
{
if (@interface.GetGenericTypeDefinition() == typeof(IList<>))
{
return true;
}
}
}
return false;
}
Use the modern pattern to build it like ASP.Net Core :
https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1
The builder add the possibility :
Tiny.RestClient is a great library. Some of us believe it could upgraded to surpass all Http Client programs
Reference to old Issue on AddUriParameter, here is an Example
public void GET_with_resource_containing_tokens()
{
RestRequest request = new RestRequest("resource/{foo}");
request.AddUrlSegment("foo", "bar");
RestClient client = new RestClient(new Uri("http://example.com"));
Uri expected = new Uri("http://example.com/resource/bar");
Uri output = client.BuildUri(request);
Assert.AreEqual(expected, output);
}
public void POST_with_resource_containing_tokens()
{
RestRequest request = new RestRequest("resource/{foo}", Method.POST);
request.AddUrlSegment("foo", "bar");
RestClient client = new RestClient(new Uri("http://example.com"));
Uri expected = new Uri("http://example.com/resource/bar");
Uri output = client.BuildUri(request);
Assert.AreEqual(expected, output);
}
Rewrite the serializers/deserializers class to support multi accept type.
I am using a release version after 8e16d65, which fixed the 'PATCH' issue.
When I post bytes data to my server, T.RC throws exception. And if I rewrite my request with Builtin HttpClient, it works fine.
var req = client.Post("upload").AddHeader("Authorization", "TOKEN_STRING") as IRequest;
var res = await req.AsMultiPartFromDataRequest()
.AddByteArray(new byte[]{0x11}, "file", "picture.png", "image/jpg")
.ExecuteAsHttpResponseMessageAsync();
throws following exception.
Exception: System.NullReferenceException: Object reference not set to an instance of an object
at System.Net.Http.MultipartContent.Dispose (System.Boolean disposing) [0x00003] in <xxx>:0
at System.Net.Http.HttpContent.Dispose () [0x00000] in <xxx>:0
at Tiny.RestClient.TinyRestClient+<ExecuteAsHttpResponseMessageResultAsync>d__25.MoveNext () [0x00164] in <xxx>:0
HttpClient implementation works as expected.
ByteArrayContent content = new ByteArrayContent(new byte[]{0x11});
content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpg");
MultipartFormDataContent formData = new MultipartFormDataContent
{
{ content,"file","picture.jpg" }
};
HttpClient http = new HttpClient { BaseAddress = new Uri("https://api.server.com") };
http.DefaultRequestHeaders.Add("Accept", "application/json");
http.DefaultRequestHeaders.Add("Authorization","TOKEN");
try
{
return await http.PostAsync("/upload", formData);
}
finally
{
formData.Dispose();
content.Dispose();
http.Dispose();
}
I couldn't get GZip result decompression to return anything but null, so I took a look.
In TinyRestClient.DecompressAsync
:
Tiny.RestClient/Tiny.RestClient/TinyRestClient.cs
Lines 784 to 791 in 213a8bc
Because this is a finally
clause instead of a catch
clause, it's always disposed. Which means the stream.CanRead
fails here:
Tiny.RestClient/Tiny.RestClient/TinyRestClient.cs
Lines 336 to 339 in 213a8bc
Would it be sufficient to switch this to a catch
? Will it be disposed later otherwise?
Can we adopt Add Uri Parameter like is implemented in RestSharp
Hi, thanks for this nice library. Wanted to know if var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
object should be created globally and 1 per application just like recommended for HttpClient
or should be used with using
pattern.
Thanks
Fuzzy element name matching would be a great addition.
Remove events to monitor the client.
Use the modern pattern like logging in ASP.Net Core.
https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1
The built-in JSON serializer uses Newtonsoft.Json.
But in ASP.NET Core 3.0, the default serializer is System.Text.Json. It would be nice if Tiny.RestClient supported it, because:
It's easy enough to implement a IFormatter
that uses System.Text.Json, but there's a bit of an impedance mismatch between the IFormatter
and System.Text.Json APIs... IFormatter
only has synchronous methods that take a Stream
. But System.Text.Json doesn't have synchronous methods that accept a stream, only async ones. And they return a ValueTask
, so we can't just use .Result
.
Maybe the solution would be to add a IAsyncFormatter
interface. If the formatter implements it, use the async methods, if not, use the sync methods.
Example :
client.GetRequest("City").ExecuteAsync();
client.PostRequest(city, "City").ExecuteAsync();
client.PutRequest(city, "City").ExecuteAsync();
client.DeleteRequest("City").ExecuteAsync();
I want to uniformly set the pre and post request processing actions
Is it possible to enable TCP Keep alive on the underlying socket used by the client?
StringWriter stringWriter = new StringWriter(new StringBuilder(256), (IFormatProvider) CultureInfo.InvariantCulture);
using (JsonTextWriter jsonTextWriter = new JsonTextWriter((TextWriter) stringWriter))
{
jsonTextWriter.Formatting = jsonSerializer.Formatting;
jsonSerializer.Serialize((JsonWriter) jsonTextWriter, value, type);
}
return stringWriter.ToString();
For example, accepts only 40 requests by / 10 seconds.
Thank you.
Tiny.RestClient is a programing-fluent HttpClient!
I use Tiny in my project for RESTful http requests. and i use the Moq library to mock my http service testings.
The internal Request class and it's internal members make it hard to verify my mock testing.
Hello,
i would like to use Tiny.RestClient in our project, but there is no license info.
Hello,
First at all thank you for this RestClient i love it.
I got some question for you i didnt find same methods form GET or POST, specially for the bearer authentication
GET Version
var response = await client.GetRequest(uriPath)
.WithOAuthBearer(_adminToken)
.WithTimeout(TimeSpan.FromSeconds(TIMEOUT_SEC))
.ExecuteAsync<object>();
POST VERSION
var responseEmail = await client.PostRequest(uriPath, myObject)
.WithOAuthBearer(_adminToken) // <=== DO NOT EXIST
.WithTimeout(TimeSpan.FromSeconds(TIMEOUT_SEC)) // <=== DO NOT EXIST
.ExecuteAsync<object>();
I think i should use like this :
.AddHeader("Authorization", "Bearer " + _adminToken)
?
and how add timeout parameter?
Thanks
=> Thomas make a great article on it : <3
https://www.thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient
For multipart and mono part request.
add multiple files dynamically
public IMultipartFromDataRequest AddFiles(List<FileMultiPart> files)
{
foreach (var file in files)
{
AddByteArray(file.Bytes, file.Name, file.FileName, file.ContentType);
}
return this;
}
public class FileMultiPart
{
public string Name { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Bytes { get; set; }
public FileMultiPart(string name, string fileName, byte[] bytes, string contentType = null)
{
Name = name;
FileName = fileName;
Bytes = bytes;
ContentType = contentType;
}
public static List<FileMultiPart> Factory(string name, List<KeyValuePair<string, byte[]>> fileKeyValuePairs) =>
fileKeyValuePairs.Select(p => new FileMultiPart(name, p.Key, p.Value))
.ToList();
}
The headers are added staticly.
Some users want an option to add the header just before sending request.
Hi,
I think that this libraries should not through exception when http 400 code is returned. The status code is an information not a crash. It is the same for 500 status code. The response can contain useful information. The exception behavior intricate the code behind. It is the consumer choice to through an Exception or not and that depends of your needs.
What do you think about?
Regards,
Hello, I'm trying to send IFormFile from razor post form, to a web API project. The controller API method is being called successfully but the object that is passed to API controller from razor view controller is null "IFormFile object".
What should I do ?
EDIT
I Tried the AddContent, and AddFileContent methods, and nothing worked. I tried to add the IFormFile object in an object of class, and in the method parameters, in first one all the object is null, and second one only IFormFile is null.
Now when we execute the request we can't read easily the response headers.
cmd.AddParameter(new
{
EmpNo = 7369,
HireDate = new DateTime(1980, 12, 17)
});
Hello
Please How can Developers upload files of application/octet-stream with Tiny.RestClient
Using Web Api MultipartFormDataStreamProvider
Can you show us a working Example
Would it be possible to deserialize the return object compared to the http status.
Example of signature of one of my methods
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(LoginAuthModel))]
[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))]
[Consumes("application/json")]
public async Task<IActionResult> Login([FromBody] LoginRequest model)
I'd like to translate the following cURL to the Tiny.RestClient request:
curl -v -u yourapikey:X -F "attachments[]=@/path/to/attachment1.ext" -F "attachments[]=@/path/to/attachment2.ext" -F "[email protected]" -F "subject=Ticket Title" -F "description=this is a sample ticket" -X POST 'https://domain.freshdesk.com/api/v2/tickets'
When I use the client to post the request:
var rs = await client.PostRequest("tickets")
.AsMultiPartFromDataRequest()
.AddString("[email protected]", "email")
.ExecuteAsStringAsync(CancellationToken.None);
...And I have a cURL listener (client.Settings.Listeners.AddCurl()
), the translated cURL is (some data stripped off):
curl -X POST [...] -d "--1c3acb07-77bd-494d-bc56-21290dcd5088
Content-Type: text/plain
Content-Disposition: form-data; name=email
[email protected]
[...]
The "email" param is passed with the -d
flag; how can I make the param passed by -F
flag?
does tiny.restclient support specifiying the local ip address to use while making the requests?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.