Introduction
AI features are becoming a normal part of web applications. Developers are adding chat assistants, document analysis, code generation, search, recommendations, and agent-based workflows to business applications.
The difficult part is not only connecting an application to an AI model. The user interface also needs to handle streaming responses, tool execution, conversation state, loading states, errors, and sometimes approval requests.
Blazor is a natural fit for these applications because it allows .NET developers to build interactive web interfaces using C# and Razor components. Microsoft has been adding AI-oriented components and integration patterns that make it easier to build streaming AI experiences and connect agent workflows to Blazor applications.
The important change is that AI is no longer limited to a simple textbox and a final response. A Blazor application can represent an ongoing AI interaction where content arrives incrementally and the agent can perform actions while the user watches the workflow.
This article explains how AI components fit into Blazor applications, how streaming works, how agent workflows can be represented, and what developers should consider before using these capabilities in production.
Why AI UI Is Different From Normal Web UI
A normal web request often follows this pattern:
User
|
v
HTTP Request
|
v
Server
|
v
Response
|
v
UI UpdateThe server performs the operation and returns a result.
AI applications often behave differently:
User
|
v
AI Request
|
v
Model Starts
|
+--> Partial Text
|
+--> Tool Call
|
+--> Tool Result
|
+--> More Text
|
v
Final ResponseThe UI therefore needs to understand that the operation is still running while information is already arriving.
This is why streaming components are useful.
What AI Components Bring to Blazor
AI-oriented Blazor components can help developers build common interaction patterns without implementing every piece of the user interface from scratch.
Typical AI UI requirements include:
Chat messages
Streaming text
Conversation history
User input
Loading indicators
Tool activity
Agent status
Error handling
Message regeneration
Rich content rendering
A simplified architecture looks like this:
Blazor Component
|
v
AI Client / Agent
|
v
AI Model
|
+---- Tools
|
+---- Data
|
+---- Business LogicThe component handles presentation while the AI service handles model interaction.
Streaming Is the Important Part
Without streaming, a user may see:
User: Explain this error.
[Loading...]
[Loading...]
[Loading...]
AI: The error occurs because...The application does not display anything until the model has completed its response.
With streaming:
User: Explain this error.
AI: The
AI: error
AI: occurs
AI: because
AI: the
AI: connection...The user sees progress immediately.
This is especially important when the model needs several seconds to generate a longer response or when an agent has to perform tools before completing the answer.
How Streaming Works in a Blazor Application
A typical streaming architecture looks like:
Blazor UI
|
v
AI Service
|
v
Streaming Response
|
+--> Chunk 1
+--> Chunk 2
+--> Chunk 3
+--> Chunk 4
|
v
Blazor ComponentThe component receives partial updates and updates its state.
Conceptually, a C# implementation may look like:
await foreach (var update in
chatClient.GetStreamingResponseAsync(messages))
{
responseText += update.Text;
await InvokeAsync(StateHasChanged);
}The exact API depends on the AI client and integration being used, but the design is the same.
The UI should update as data arrives instead of waiting for the entire operation.
Why Streaming Improves User Experience
Streaming does more than make an application look faster.
It gives the user feedback that the request is being processed.
This matters when:
The prompt is large
The response is long
The agent uses tools
External services are called
Retrieval is required
The model takes time to reason
Multiple operations happen before the final response
For example:
User Request
|
v
Search Documents
|
v
Retrieve Results
|
v
Call AI Model
|
v
Generate AnswerA non-streaming UI may show only a spinner during the entire process.
A streaming UI can provide useful information as the workflow progresses.
Blazor Server vs Blazor WebAssembly
The deployment model affects how an AI application should be designed.
In a Blazor Server-style application, components execute on the server and communicate with the browser over the Blazor connection.
A simplified architecture is:
Browser
|
| Blazor Connection
v
ASP.NET Core
|
v
AI ServiceIn a client-side WebAssembly application:
Browser
|
v
Blazor WebAssembly
|
| HTTPS
v
ASP.NET Core API
|
v
AI ServiceThe second architecture is especially important for security.
You generally should not place sensitive AI provider credentials directly into browser-side application code.
The browser should call your backend, and the backend should manage access to protected AI services.
Keep AI Credentials on the Server
This is a critical production rule.
Do not do this:
Browser
|
+-- AI API Key
|
v
AI ProviderInstead:
Browser
|
v
Your API
|
| Secure Credentials
v
AI ProviderThe backend can enforce:
Authentication
Authorization
Rate limits
Usage policies
Prompt controls
Logging
Data filtering
The Blazor component should not become a place where sensitive provider credentials are exposed.
Building a Simple AI Chat Component
A simple Blazor component can maintain a conversation in memory.
For example:
@page "/assistant"
<h3>AI Assistant</h3>
<div class="chat">
@foreach (var message in messages)
{
<div class="message">
<strong>@message.Role:</strong>
@message.Content
</div>
}
</div>
<input @bind="prompt" />
<button @onclick="SendAsync">Send</button>
@code {
private string prompt = string.Empty;
private readonly List<ChatMessageViewModel> messages = [];
private async Task SendAsync()
{
if (string.IsNullOrWhiteSpace(prompt))
{
return;
}
messages.Add(
new ChatMessageViewModel("User", prompt));
var currentPrompt = prompt;
prompt = string.Empty;
await SendToAgentAsync(currentPrompt);
}
}This example focuses on the UI structure.
The AI service should be kept outside the component rather than putting model communication directly into the Razor file.
Keep AI Logic Outside the Component
A common beginner implementation puts everything into the .razor component:
Razor Component
|
+-- UI
+-- Prompt
+-- Authentication
+-- AI Client
+-- Database
+-- Tool Calls
+-- LoggingThis becomes difficult to maintain.
A better structure is:
Blazor Component
|
v
IAssistantService
|
+-- AI Client
+-- Conversation Store
+-- Tool Service
+-- Authorization
+-- LoggingThe component should primarily manage UI state.
The service should own AI-related application behavior.
Streaming Through an Application Service
A service can expose a streaming API to the component.
For example:
public interface IAssistantService
{
IAsyncEnumerable<string> StreamResponseAsync(
string prompt,
CancellationToken cancellationToken);
}The implementation can then connect to the AI client:
public async IAsyncEnumerable<string> StreamResponseAsync(
string prompt,
[EnumeratorCancellation]
CancellationToken cancellationToken)
{
await foreach (var update in
chatClient.GetStreamingResponseAsync(
prompt,
cancellationToken))
{
if (!string.IsNullOrEmpty(update.Text))
{
yield return update.Text;
}
}
}The component consumes the stream:
await foreach (var chunk in
assistantService.StreamResponseAsync(
prompt,
cancellationToken))
{
response += chunk;
await InvokeAsync(StateHasChanged);
}This separation makes the system easier to test and change.
AI Agent Workflows in Blazor
A chatbot is only one type of AI application.
An agent can perform a sequence of actions.
For example:
User
|
v
"Find the customer's open invoices."
|
v
Agent
|
+--> Customer Service Tool
|
+--> Database Query
|
+--> Invoice Service
|
v
ResponseThe UI should represent more than the final text.
A useful interface might show:
Analyzing request...
Searching customer record...
Checking invoices...
Preparing response...This makes an agent workflow understandable to the user.
Tool Calls Should Be Visible When Appropriate
Suppose an agent calls an internal database service.
The user does not necessarily need to see every technical parameter.
But showing meaningful progress can help:
Searching customer account
Checking open invoices
Preparing summaryThis is better than displaying a generic spinner for 20 seconds.
The UI should communicate useful state without exposing sensitive internal information.
Human Approval in Agent Workflows
Some agent actions should require user approval.
For example:
Agent wants to:
Send customer email
|
v
Blazor UI
[Approve] [Reject]Another example:
Agent wants to:
Create a production deployment
|
v
Explicit confirmation requiredThe UI should make the action clear.
Do not hide important side effects behind a generic "Continue" button.
Handling Tool Errors
Agent tools can fail.
For example:
Agent
|
v
Customer API
|
X
Timeout
|
v
Agent
|
v
Recovery / ExplanationThe UI should not simply display:
Something went wrong.A better user-facing message might be:
The customer service could not be reached.
No changes were made. Please try again.The technical error should be logged separately.
Cancellation Matters
Long-running AI operations should be cancellable.
For example:
[Generating response...]
[Stop]The user may realize that the request was incorrect and want to stop it.
The backend should propagate cancellation:
using var cts = new CancellationTokenSource();
await foreach (var update in
assistantService.StreamResponseAsync(
prompt,
cts.Token))
{
response += update;
}When the user clicks Stop:
cts.Cancel();Cancellation becomes even more important for agent workflows because the agent may otherwise continue executing tools after the user no longer wants the operation.
Conversation State
A production AI application usually needs conversation state.
A simple model could be:
public sealed class ConversationMessage
{
public long Id { get; set; }
public string Role { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public DateTime CreatedAtUtc { get; set; }
}The conversation can then be stored in a database rather than only inside the browser session.
For example:
Blazor
|
v
Assistant Service
|
v
Conversation Store
|
v
Azure SQLThis makes it possible to restore a conversation after the user reconnects.
Do Not Store Everything in Browser State
Keeping a small amount of temporary UI state in the browser is normal.
But long-lived conversation history, sensitive information, and business records should be stored according to the application's security and retention requirements.
A production architecture should define:
What is stored
How long it is stored
Who can access it
Whether users can delete it
Whether sensitive data is filtered
How the data is encrypted
AI conversations can contain confidential business information, so treating them like ordinary UI state can create unnecessary risk.
Streaming and Rendering Performance
Streaming every tiny token directly into a complex component can create excessive rendering activity.
For example:
Token
Token
Token
Token
Token
Token
Token
...If every token causes a full component render, the UI can perform unnecessary work.
A better approach can be to buffer small updates and render them in controlled batches.
Conceptually:
Incoming Tokens
|
v
Small Buffer
|
v
UI UpdateThe exact buffering strategy depends on the component tree and application requirements.
The goal is to keep streaming responsive without creating unnecessary rendering overhead.
Accessibility Matters
AI interfaces should be accessible.
When text streams into a page, users relying on assistive technologies need an understandable experience.
Consider:
Proper semantic HTML
Keyboard navigation
Focus management
Accessible status messages
Clear approval controls
Readable error messages
Avoiding excessive live-region announcements
Do not announce every small token as a separate accessibility event.
A streamed AI response should feel like one coherent message to the user.
Security Considerations
AI components do not remove normal web application security requirements.
A Blazor AI application should still enforce:
Authentication
Authorization
Input validation
Output handling
Rate limiting
CSRF protections where applicable
Secure credential storage
Logging and auditing
There is another concern specific to AI applications: prompt injection.
Suppose an agent reads an external document:
Invoice.pdf
|
v
Document Content
|
v
AI AgentThe document might contain text that attempts to influence the agent.
The agent should not automatically treat every piece of retrieved content as a trusted instruction.
This becomes especially important when agents have access to tools.
Protect Tool Permissions
An agent that can only answer questions has a smaller security surface than an agent that can:
Read Database
Write Database
Send Email
Deploy Application
Delete RecordsBlazor provides the user interface, but the backend must enforce authorization.
Do not rely on hiding a button in the UI to prevent unauthorized operations.
For example:
[Authorize(Policy = "CanSendCustomerEmail")]
public async Task SendCustomerEmailAsync(...)
{
// Execute action.
}The authorization decision should happen on the server.
Common Mistakes
Putting API Keys in the Blazor Client
Browser code is not a secure location for long-lived AI provider secrets.
Use a protected backend service.
Making the UI Responsible for Business Rules
The UI should not decide whether an agent can modify a customer record.
That decision belongs in the backend authorization and business-logic layers.
Treating Streaming as Only a Visual Effect
Streaming should be integrated into the application lifecycle. The application needs to handle cancellation, errors, reconnects, partial responses, and completion.
Ignoring Long-Running Operations
An agent may take considerably longer than a normal HTTP request.
Design for cancellation and meaningful progress information.
Showing Technical Errors Directly to Users
Stack traces, provider errors, internal URLs, and database details should not be displayed as user-facing messages.
Log technical details securely and return a useful explanation to the user.
Best Practices
Keep the Component Thin
Use the Razor component for presentation and interaction state.
Put AI calls, tool execution, data access, and authorization into services.
Use Streaming for Long Responses
Streaming provides a better experience when model responses or agent operations take time.
Make Side Effects Explicit
If an agent is about to change something important, show the user what will happen and require approval where appropriate.
Propagate Cancellation
When the user stops an operation, pass the cancellation token through the entire call chain.
Store Important State Server-Side
Use a persistent store for conversations and business information that needs to survive reconnections or sessions.
Monitor Agent Operations
Track latency, failures, cancellations, tool errors, and model errors.
This makes production troubleshooting much easier.
Keep the Model Behind an Abstraction
Use an AI client abstraction so the Blazor application is not tightly coupled to one model provider.
That makes future provider or model changes easier.
Advantages
Natural Fit for .NET Teams
Blazor allows developers who already know C#, ASP.NET Core, dependency injection, and Razor components to build AI-powered web experiences without introducing an entirely separate frontend programming model. This can reduce the number of technologies a .NET team needs to maintain.
Better Streaming Experiences
AI responses can take time, especially when an agent performs multiple operations. Streaming allows the interface to display partial output and useful progress instead of leaving users with an inactive screen while the backend is working.
Reusable Component Architecture
AI interaction patterns can be encapsulated into reusable Razor components and services. Once a team has a well-designed chat, streaming, approval, and error-handling pattern, the same architecture can be reused across different parts of an enterprise application.
Strong Integration With ASP.NET Core
Blazor applications can use the existing ASP.NET Core ecosystem for authentication, authorization, dependency injection, configuration, logging, APIs, and data access. This makes it easier to place AI features inside an existing enterprise application rather than creating a separate AI frontend.
Good Fit for Agent Workflows
Agent applications need more than a text box. They need state, tool calls, progress, approvals, and cancellation. Blazor's component model provides a useful foundation for representing these interactive states in a structured way.
Disadvantages
Streaming Adds Application Complexity
A streaming response is more complicated than a normal request-response operation. Developers need to handle partial output, cancellation, errors, reconnection behavior, and UI rendering efficiently. This requires more careful design than simply displaying a completed response.
Agent Interfaces Can Become Complex
Once an application starts showing tool calls, approvals, progress states, sources, errors, and intermediate results, the UI can quickly become difficult to manage. Without clear component boundaries, a single AI component can grow into a large collection of conditional rendering logic.
Server-Side Resource Usage Can Increase
AI interactions can remain active for longer than traditional HTTP requests. Streaming connections, concurrent conversations, tool execution, and state management can increase server resource usage, so production systems need appropriate capacity planning.
Security Requirements Are Higher
An AI application can expose sensitive information or perform actions based on user requests. Developers therefore need to combine normal web security with AI-specific controls such as prompt-injection defenses, tool authorization, data filtering, and careful output handling.
Model Behavior Is Not Fully Deterministic
The same interface can receive different responses from the underlying model. This makes traditional UI testing insufficient for the complete AI workflow. Teams need to test the surrounding application behavior separately from the exact generated text.
Troubleshooting
The UI Shows a Spinner but No Response
Check whether the backend is actually streaming data and whether the Blazor component is consuming the stream correctly.
Also check browser developer tools and server logs for connection failures.
The Response Appears Only at the End
The application may be buffering the response instead of forwarding streaming updates.
Check the AI client, backend endpoint, and component rendering path.
The UI Becomes Slow During Streaming
Check how frequently the component calls StateHasChanged.
If every tiny token triggers a full render, introduce controlled buffering.
Cancellation Does Not Stop the Agent
Verify that the same cancellation token is propagated through the Blazor component, service layer, AI client, and tool calls.
Cancelling only the UI loop does not necessarily stop backend work.
Agent Tools Are Unauthorized
Do not rely on the UI to enforce permissions.
Check the backend authorization policy and the identity under which the tool executes.
Conversations Disappear After Refresh
The application is probably storing conversation state only in memory.
Use a persistent conversation store when the business requirement requires conversations to survive refreshes or reconnections.
A Production Architecture
A scalable Blazor AI application can be organized like this:
Browser
|
v
Blazor Components
|
v
Application Service
|
+------------+------------+
| |
v v
Conversation Store AI Client
| |
v v
Database AI Model
|
+----------+----------+
| |
v v
Tools Retrieval
|
v
Enterprise SystemsEach layer has a specific responsibility.
The Blazor component manages interaction.
The application service coordinates the operation.
The conversation store manages persistence.
The AI client communicates with the model.
Tools provide controlled access to external systems.
This separation makes the application easier to test and maintain.
When Should You Use AI Components in Blazor?
Blazor AI components are particularly useful when you are building:
Internal developer assistants
Enterprise chat applications
Customer-support interfaces
Document assistants
Knowledge-base applications
AI-powered dashboards
Agent workflows
Approval-based automation
AI copilots inside existing .NET applications
They are less useful when the requirement is only a simple server-side AI call with no interactive user experience.
In that case, a normal service endpoint may be sufficient.
Summary
Blazor is well suited to AI applications because its component model can represent the dynamic state of an agent interaction. With streaming, the interface can display responses while they are being generated instead of waiting for the entire operation to finish.
The bigger opportunity is agent workflows. A modern AI application may involve tools, approvals, shared state, external services, and long-running operations. Blazor components can represent those states while ASP.NET Core services keep the business and security logic on the server.
The most important design principle is to keep the UI separate from the AI and business logic. A Razor component should not contain provider credentials, database logic, authorization rules, and agent orchestration all in one place.
For production applications, focus on streaming, cancellation, authorization, persistent state, error handling, accessibility, and monitoring. AI makes the interface more dynamic, but it also introduces new failure and security scenarios that traditional CRUD applications do not normally face.
When those concerns are designed properly, Blazor provides a practical way for .NET teams to build AI-powered applications without abandoning the architecture and development practices they already use.

Join the conversation! Your thoughts help the community grow.