|
| 1 | +--- |
| 2 | +sidebar_position: 3 |
| 3 | +title: Creating the client |
| 4 | +--- |
| 5 | + |
| 6 | +## Constructors |
| 7 | + |
| 8 | +A RestSharp client can be instantiated by one of its constructors. Two most commonly used constructors are: |
| 9 | + |
| 10 | +#### Only specify the base URL |
| 11 | + |
| 12 | +You can create an instance of `RestClient` with only a single parameter: the base URL. Even that isn't required as base URL can be left empty. In that case, you'd need to specify the absolute path for each call. When the base URL is set, you can use both relative and absolute path. |
| 13 | + |
| 14 | +```csharp |
| 15 | +// Creates a client with default options to call a given base URL |
| 16 | +var client = new RestClient("https://localhost:5000"); |
| 17 | +``` |
| 18 | + |
| 19 | +#### Provide client options |
| 20 | + |
| 21 | +The most common way to create a client is to use the constructor with options. The options object has the type of `RestClientOptions`. |
| 22 | +Here's an example of how to create a client using the same base path as in the previous sample, but with a couple additional settings: |
| 23 | + |
| 24 | +```csharp |
| 25 | +// Creates a client using the options object |
| 26 | +var options = new RestClientOptions("https://localhost:5000") { |
| 27 | + MaxTimeout = 1000 |
| 28 | +}; |
| 29 | +var client = new RestClient(options); |
| 30 | +``` |
| 31 | + |
| 32 | +#### Advanced configuration |
| 33 | + |
| 34 | +RestSharp can be configured with more tweaks, including default request options, how it should handle responses, how serialization works, etc. You can also provide your own instance of `HttpClient` or `HttpMessageHandler`. |
| 35 | + |
| 36 | +Read more about the advanced configuration of RestSharp on a [dedicated page](../advanced/configuration.md). |
| 37 | + |
| 38 | +## Simple factory |
| 39 | + |
| 40 | +Another way to create the client instance is to use a simple client factory. The factory will use the `BaseUrl` property of the client options to cache `HttpClient` instances. Every distinct base URL will get its own `HttpClient` instance. Other options don't affect the caching. Therefore, if you use different options for the same base URL, you'll get the same `HttpClient` instance, which will not be configured with the new options. Options that aren't applied _after_ the first client instance is created are: |
| 41 | + |
| 42 | +* `Credentials` |
| 43 | +* `UseDefaultCredentials` |
| 44 | +* `AutomaticDecompression` |
| 45 | +* `PreAuthenticate` |
| 46 | +* `FollowRedirects` |
| 47 | +* `RemoteCertificateValidationCallback` |
| 48 | +* `ClientCertificates` |
| 49 | +* `MaxRedirects` |
| 50 | +* `MaxTimeout` |
| 51 | +* `UserAgent` |
| 52 | +* `Expect100Continue` |
| 53 | + |
| 54 | +Constructor parameters to configure the `HttpMessageHandler` and default `HttpClient` headers configuration are also ignored for the cached instance as the factory only configures the handler once. |
| 55 | + |
| 56 | +You need to set the `useClientFactory` parameter to `true` in the `RestClient` constructor to enable the factory. |
| 57 | + |
| 58 | +```csharp |
| 59 | +var client = new RestClient("https://api.twitter.com/2", true); |
| 60 | +``` |
| 61 | + |
| 62 | +## Reusing HttpClient |
| 63 | + |
| 64 | +RestSharp uses `HttpClient` internally to make HTTP requests. It's possible to reuse the same `HttpClient` instance for multiple `RestClient` instances. This is useful when you want to share the same connection pool between multiple `RestClient` instances. |
| 65 | + |
| 66 | +One way of doing it is to use `RestClient` constructors that accept an instance of `HttpClient` or `HttpMessageHandler` as an argument. Note that in that case not all the options provided via `RestClientOptions` will be used. Here is the list of options that will work: |
| 67 | + |
| 68 | +- `BaseAddress` is be used to set the base address of the `HttpClient` instance if base address is not set there already. |
| 69 | +- `MaxTimeout` is used to cancel the call using the cancellation token source, so |
| 70 | +- `UserAgent` will be added to the `RestClient.DefaultParameters` list as a HTTP header. This will be added to each request made by the `RestClient`, and the `HttpClient` instance will not be modified. This is to allow the `HttpClient` instance to be reused for scenarios where different `User-Agent` headers are required. |
| 71 | +- `Expect100Continue` |
| 72 | + |
| 73 | +Another option is to use a simple HTTP client factory as described [above](#simple-factory). |
| 74 | + |
| 75 | +## Blazor support |
| 76 | + |
| 77 | +Inside a Blazor webassembly app, you can make requests to external API endpoints. Microsoft examples show how to do it with `HttpClient`, and it's also possible to use RestSharp for the same purpose. |
| 78 | + |
| 79 | +You need to remember that webassembly has some platform-specific limitations. Therefore, you won't be able to instantiate `RestClient` using all of its constructors. In fact, you can only use `RestClient` constructors that accept `HttpClient` or `HttpMessageHandler` as an argument. If you use the default parameterless constructor, it will call the option-based constructor with default options. The options-based constructor will attempt to create an `HttpMessageHandler` instance using the options provided, and it will fail with Blazor, as some of those options throw thw "Unsupported platform" exception. |
| 80 | + |
| 81 | +Here is an example how to register the `RestClient` instance globally as a singleton: |
| 82 | + |
| 83 | +```csharp |
| 84 | +builder.Services.AddSingleton(new RestClient(new HttpClient())); |
| 85 | +``` |
| 86 | + |
| 87 | +Then, on a page you can inject the instance: |
| 88 | + |
| 89 | +```html |
| 90 | +@page "/fetchdata" |
| 91 | +@using RestSharp |
| 92 | +@inject RestClient _restClient |
| 93 | +``` |
| 94 | + |
| 95 | +And then use it: |
| 96 | + |
| 97 | +```csharp |
| 98 | +@code { |
| 99 | + private WeatherForecast[]? forecasts; |
| 100 | + |
| 101 | + protected override async Task OnInitializedAsync() { |
| 102 | + forecasts = await _restClient.GetJsonAsync<WeatherForecast[]>("http://localhost:5104/weather"); |
| 103 | + } |
| 104 | + |
| 105 | + public class WeatherForecast { |
| 106 | + public DateTime Date { get; set; } |
| 107 | + public int TemperatureC { get; set; } |
| 108 | + public string? Summary { get; set; } |
| 109 | + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); |
| 110 | + } |
| 111 | +} |
| 112 | +``` |
| 113 | + |
| 114 | +In this case, the call will be made to a WebAPI server hosted at `http://localhost:5104/weather`. Remember that if the WebAPI server is not hosting the webassembly itself, it needs to have a CORS policy configured to allow the webassembly origin to access the API endpoint from the browser. |
0 commit comments