Fetch
How to use the Fetch class of the bit Butil?
Usage
The Fetch class wraps the browser's
Fetch API
with progress reporting and an abortable handle. Prefer HttpClient for normal API calls;
reach for this when you need progress for big downloads or fetch-only semantics. Inject it and use it like this:
@inject Bit.Butil.Fetch fetch
@code {
var response = await fetch.Send(new FetchRequest { Url = "https://..." },
onProgress: p => { /* bytes received */ });
}Methods
Send:
Sends the request and returns the full FetchResponse (status, headers and body bytes).
Send with progress and cancellation:
Pass an onProgress callback to watch bytes arrive, and a CancellationToken to abort mid-flight.
Sends the request and returns the full FetchResponse (status, headers and body bytes).
@inject Bit.Butil.Fetch fetch
<BitTextField @bind-Value="url" Label="URL" />
<BitButton OnClick="SendGet">Send GET</BitButton>
<div>@sendGetStatus</div>
<pre>@sendGetBody</pre>
@code {
private string url = "https://jsonplaceholder.typicode.com/todos/1";
private string? sendGetStatus;
private string? sendGetBody;
private async Task SendGet()
{
var response = await fetch.Send(new FetchRequest { Url = url.Trim() });
if (response.Error is not null)
{
sendGetStatus = $"Error: {response.Error}";
return;
}
sendGetStatus = $"Status {response.Status} {response.StatusText} - {response.Body.Length} bytes from {response.Url}";
sendGetBody = System.Text.Encoding.UTF8.GetString(response.Body);
}
}Send with progress and cancellation:
Pass an onProgress callback to watch bytes arrive, and a CancellationToken to abort mid-flight.
@inject Bit.Butil.Fetch fetch
<BitButton OnClick="SendWithProgress">Download with progress</BitButton>
<BitButton OnClick="AbortRequest">Abort</BitButton>
<div>@progressText</div>
@code {
private string? progressText;
private CancellationTokenSource? cts;
private async Task SendWithProgress()
{
cts?.Dispose();
cts = new CancellationTokenSource();
var response = await fetch.Send(
new FetchRequest { Url = "https://jsonplaceholder.typicode.com/photos" },
onProgress: p =>
{
progressText = p.Total.HasValue
? $"Received {p.Loaded} / {p.Total} bytes"
: $"Received {p.Loaded} bytes";
InvokeAsync(StateHasChanged);
},
cancellationToken: cts.Token);
progressText = response.Aborted ? "Aborted" : "Complete";
}
private void AbortRequest() => cts?.Cancel();
}