Streaming Json response with IAsyncEnumerable in .net 6.0 and example fetch in javascript
Hi, We will get the data as stream using IAsyncEnumerable and example with javascript fetch.
Let’s create project as .net 6.0 or higher because there is no support for stream data in versions below .net 6.0.
A example endpoint:
1 2 3 4 5 6 7 8 9 10 11 |
[HttpGet("testasync")] public async IAsyncEnumerable<UserModel> GetValues() { var values = new[] { "Okan", "Jack","Banu","Ronaldo" }; var counter = 0; foreach (var item in values) { await Task.Delay(1000); yield return new UserModel { Id = ++counter,Name=item,BirthDate= RandomDay().ToString("d")}; } } |
Minimal api:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
app.MapGet("/minimalasync", () => { async IAsyncEnumerable<string> FetchData() { var values = new[] { "value1", "value2", "value3","value4" }; foreach (var item in values) { await Task.Delay(1000); yield return item; } } return FetchData(); }); |
How to fetch data as stream in javascript?
We will do using ReadableStream.getReader(). source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const getItems = () => fetch("/test/testasync").then(async response => { const reader = response.body?.getReader(); if (!reader) { return; } const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; var item = decoder.decode(value).replace(/\[|]/g, '').replace(/^,/, ''); var parsedItem = JSON.parse(item); var row = document.createElement("tr"); var idCell = document.createElement("td"); var nameCell = document.createElement("td"); var birthDateCell = document.createElement("td"); idCell.innerHTML = parsedItem.id; nameCell.innerHTML = parsedItem.name; birthDateCell.innerHTML = parsedItem.birthDate; row.appendChild(idCell); row.appendChild(nameCell); row.appendChild(birthDateCell); table.appendChild(row); } reader.releaseLock(); }); |
Page:
Method GetValues() has return type “IAsyncEnumerable”, so it should return items of type “string”, but it returns items of type UserModel. Does UserModel have “implicit operator string”?
I’m sorry. You’re right. Return type should be IAsyncEnumerable. I have updated. thank you.