Skip to content

Commit 884b80e

Browse files
committed
Added a Blazor note
1 parent 47b5c82 commit 884b80e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/usage.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,3 +359,44 @@ var statusCode = client.PostJsonAsync("orders", request, cancellationToken);
359359
```
360360

361361
The same two extensions also exist for `PUT` requests (`PutJsonAsync`);
362+
363+
## Blazor support
364+
365+
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.
366+
367+
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.
368+
369+
Here is an example how to register the `RestClient` instance globally as a singleton:
370+
371+
```csharp
372+
builder.Services.AddSingleton(new RestClient(new HttpClient()));
373+
```
374+
375+
Then, on a page you can inject the instance:
376+
377+
```html
378+
@page "/fetchdata"
379+
@using RestSharp
380+
@inject RestClient _restClient
381+
```
382+
383+
And then use it:
384+
385+
```csharp
386+
@code {
387+
private WeatherForecast[]? forecasts;
388+
389+
protected override async Task OnInitializedAsync() {
390+
forecasts = await _restClient.GetJsonAsync<WeatherForecast[]>("http://localhost:5104/weather");
391+
}
392+
393+
public class WeatherForecast {
394+
public DateTime Date { get; set; }
395+
public int TemperatureC { get; set; }
396+
public string? Summary { get; set; }
397+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
398+
}
399+
}
400+
```
401+
402+
In this case, the call will be made to a WebAPI server hosted at `http://localhost:5104/weather`. Remember that if this server is not hosting the webassembly itself, it needs to have a CORS policy configure to allow the webassembly host URL to access the API endpoint in the browser.

0 commit comments

Comments
 (0)