Fluent REST client.
RestClient
The RestClient is an abstract class that provides fluent methods to query REST services.
public class MyService : RestClient
{
public MyService(string baseUrl) : base(baseUrl)
{
}
public async Task<User[]> GetUsers(string searchText)
{
return await Get($"{BaseUrl}/users")
.QueryParameter("search", searchText)
.ReadJson<User[]>();
}
public async Task UpdateUser(User user, bool activate)
{
await Post($"{BaseUrl}/users/update")
.QueryParameter("activate", activate)
.JsonContent(user)
.ReadString();
}
}
- The fluent call starts with
Get,Post,Put,Patch, etc... - The following calls apply optional parameters to the HTTP request:
QueryParameterStringContentJsonContentFormUrlEncodedContentMultipartFileContentandMultipartStringContent
- Finally, execute the REST request by calling either of the following:
ReadStringReadByteArrayReadJson
RestException
If a RestClient encounters an error, a RestException is thrown:
try
{
MyService myService = new("http://api.exmample.com");
User[] users = await myService.GetUsers();
}
catch (RestException ex)
{
Console.WriteLine(ex.StatusCode);
Console.WriteLine(ex.Content); // The HTML body
}
RestRequestOptions
Modify the properties in RestClient.RequestOptions to configure formats, etc. of REST request:
public class MyService : RestClient
{
public MyService(string baseUrl) : base(baseUrl)
{
RequestOptions.QueryParameterDateTimeFormat = "dd.MM.yyyy HH:mm:ss";
RequestOptions.QueryParameterDateOnlyFormat = "dd.MM.yyyy";
RequestOptions.QueryParameterTimeOnlyFormat = "HH:mm:ss";
}
}
The configured formats are used in RestRequest.QueryParameter.
- change: Targeting .NET 10.0
- new:
RestRequestextended all methods withCancellationTokenparameter
- change: Targeting .NET 9.0
- new: Server-sent events using
RestRequest.ReadEvents, method - new:
RestClient.DisableCertificateValidationproperty - new:
RestRequest.RestClient,HttpMethod, andUrlproperties - new:
RestRequest.Execute, method - new:
BytecodeApi.Rest.GenericRestClientclass
- new:
RestRequest.Headermethod
- new:
RestRequest.ReadFilemethod
- new:
RestClient.RequestOptionsproperty - new:
RestRequest.MultipartFileContentandMultipartStringContentmethods - new:
RestRequest.ReadByteArraywith progress callback - new:
RestRequestOptionsclass
- Initial release
