Exercise 1: Unary gRPC Call in Blazor Server - "Say Hello"
๐งช Exercise 1: Unary gRPC Call in Blazor Server - "Say Hello"
This hands-on exercise will guide you through creating a simple "Hello World" application that uses a unary gRPC call. You will build an **ASP.NET Core gRPC Service** and a **Blazor Server client** to consume it. This will solidify your understanding of how gRPC services are defined, implemented, and called from a client application.
✅ Step 1: Setup gRPC Service in ASP.NET Core
First, we'll create the gRPC server that the Blazor app will call.
1. Create an Empty ASP.NET Core Web App
Using the .NET CLI or Visual Studio, create a new project.
// Using the .NET CLI
dotnet new web -n GrpcServerDemo
Name your project `GrpcServerDemo`.
2. Add NuGet Packages
Add the necessary packages for gRPC to your server project.
dotnet add package Grpc.AspNetCore
dotnet add package Google.Protobuf
dotnet add package Grpc.Tools
3. Add `greeter.proto` to a new `Protos` folder
Create a new folder named `Protos` and add a file named `greeter.proto`. This file defines the contract for our service.
syntax = "proto3";
// Defines the C# namespace for the generated classes
option csharp_namespace = "GrpcServerDemo";
// Defines the Greeter service with a single method
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
// Defines the message for the request
message HelloRequest {
string name = 1;
}
// Defines the message for the response
message HelloReply {
string message = 1;
}
4. Update `.csproj`
You need to tell the build system to generate server-side code from the `.proto` file.
<ItemGroup>
<Protobuf Include="Protos\greeter.proto" GrpcServices="Server" />
</ItemGroup>
5. Implement the service
Create a `Services` folder and add `GreeterService.cs`. This class will contain the logic for our gRPC method.
// Services/GreeterService.cs
using Grpc.Core;
using GrpcServerDemo; // Use the namespace from your proto file
public class GreeterService : Greeter.GreeterBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = $"Hello, {request.Name}! Welcome to gRPC."
});
}
}
6. Configure `Program.cs`
Finally, configure your ASP.NET Core application to use gRPC and map your service.
var builder = WebApplication.CreateBuilder(args);
// Add gRPC services to the container
builder.Services.AddGrpc();
var app = builder.Build();
// Map our GreeterService to handle incoming gRPC requests
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client.");
app.Run();
Your gRPC server is now complete! Run the project to ensure it builds successfully, but note that you'll need a client to interact with it.
✅ Step 2: Create a Blazor Server App - `BlazorGrpcClient`
Next, we'll build the Blazor Server application that will call our gRPC service.
1. Add NuGet Packages
In your new Blazor Server project, add the client-side gRPC packages.
dotnet add package Grpc.Net.Client
dotnet add package Google.Protobuf
dotnet add package Grpc.Tools
You'll also need to add a reference to your server project so the Blazor app can use the generated types.
dotnet add reference ..\GrpcServerDemo\GrpcServerDemo.csproj
2. Add `greeter.proto` again in `Protos` folder
Copy the exact same `greeter.proto` file into a `Protos` folder in your Blazor project.
3. Update `.csproj`
This time, we'll configure the `.csproj` file to generate client-side code from the `.proto` file.
<ItemGroup>
<Protobuf Include="Protos\greeter.proto" GrpcServices="Client" />
</ItemGroup>
The `GrpcServices` attribute is now set to `"Client"`.
4. Add gRPC Client to `Program.cs`
Configure the gRPC client in Blazor's `Program.cs` file using dependency injection.
// Program.cs
using Grpc.Net.Client;
using GrpcServerDemo;
var builder = WebApplication.CreateBuilder(args);
// ... other services ...
// Configure the gRPC client as a singleton to be injected into components
builder.Services.AddSingleton(services =>
{
// The address of your gRPC server
var channel = GrpcChannel.ForAddress("https://localhost:7001");
// Create and return the client instance
return new Greeter.GreeterClient(channel);
});
// ... other app configuration ...
5. Create a Razor Component - `Pages/SayHello.razor`
Finally, create a new Razor component to serve as the UI for our gRPC call.
@page "/sayhello"
@inject GrpcServerDemo.Greeter.GreeterClient GreeterClient
<h3>Say Hello (Unary gRPC)</h3>
<p>This component calls a gRPC service from the Blazor Server.</p>
<div class="input-group mb-3">
<input type="text" class="form-control" @bind="Name" placeholder="Enter your name" aria-label="Recipient's username" aria-describedby="button-addon2">
<button class="btn btn-primary" type="button" id="button-addon2" @onclick="CallSayHello">Greet</button>
</div>
<h4>Server Response:</h4>
<p>@ResponseMessage</p>
@code {
private string Name { get; set; } = "World";
private string ResponseMessage { get; set; } = "Awaiting call...";
private async Task CallSayHello()
{
// Use the injected client to make the gRPC call
var reply = await GreeterClient.SayHelloAsync(new HelloRequest { Name = Name });
ResponseMessage = reply.Message;
}
}
Now you can run both projects simultaneously (e.g., by setting both as startup projects in Visual Studio). Navigate to `/sayhello` in your Blazor app, enter a name, and click "Greet" to see the response from your gRPC service.
Comments
Post a Comment