gRPC changes how backend services communicate. Instead of sending loosely structured JSON over traditional HTTP endpoints, gRPC uses strongly typed contracts defined with Protocol Buffers and communicates over HTTP/2.
For ASP.NET Core developers, the challenge is usually not creating the first gRPC service. The harder part is preparing an existing application so that gRPC traffic works reliably alongside authentication, authorization, logging, health checks, streaming, deployment, and traditional REST APIs.
A well-prepared ASP.NET Core application can support both REST and gRPC without forcing every client to use the same communication model.
Understanding Where gRPC Fits
REST and gRPC solve different problems.
REST is usually a good choice when APIs are consumed directly by browsers, external clients, or systems where HTTP and JSON provide a simple integration model.
gRPC is particularly useful for internal services, high-frequency service-to-service communication, strongly typed contracts, and streaming scenarios.
A typical application may therefore expose both:
ASP.NET Core Application
|
+-- REST API
|
+-- gRPC Services
|
+-- Health Endpoints
|
+-- Authentication
|
+-- ObservabilityThe important point is that gRPC should be treated as another first-class communication layer rather than an isolated feature added to an existing project.
Define the Contract First
gRPC APIs are based on .proto files.
A simple contract might look like this:
syntax = "proto3";
option csharp_namespace = "Catalog.Contracts";
package catalog;
service CatalogService {
rpc GetProduct (GetProductRequest) returns (ProductReply);
}
message GetProductRequest {
int32 id = 1;
}
message ProductReply {
int32 id = 1;
string name = 2;
double price = 3;
}The contract defines the service method and the request and response messages.
This gives both sides a common interface. The client and server can generate strongly typed code from the same contract instead of manually maintaining JSON models and endpoint documentation.
Keep contracts focused. Avoid creating a single service containing dozens of unrelated operations.
Add gRPC to ASP.NET Core
The ASP.NET Core application needs the gRPC services registered during startup.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.MapGrpcService<CatalogService>();
app.Run();This allows the same application to expose both conventional API controllers and gRPC services.
For example:
/api/productscan remain a REST endpoint while:
catalog.CatalogService/GetProductis handled by the gRPC service.
Configure HTTP/2 Correctly
The HTTP protocol configuration is one of the most important parts of a gRPC deployment.
gRPC requires HTTP/2 for normal gRPC communication. The server therefore needs an HTTPS endpoint configured for HTTP/2.
A Kestrel configuration can explicitly define the protocol:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://0.0.0.0:5001",
"Protocols": "Http2"
}
}
}
}For an application serving both REST and gRPC traffic, you may need to support HTTP/1.1 and HTTP/2 on the same endpoint.
Kestrel can negotiate the protocol using HTTPS and ALPN:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://0.0.0.0:5001",
"Protocols": "Http1AndHttp2"
}
}
}
}This configuration is useful when the same application needs to handle conventional HTTP APIs and gRPC traffic.
The exact protocol configuration should match the deployment architecture. If a reverse proxy or gateway sits in front of the application, verify that it also supports the required HTTP/2 path.
Keep REST and gRPC Models Separate
One common mistake is trying to reuse every model between REST and gRPC.
For example, a REST API might use:
public sealed record ProductResponse(
int Id,
string Name,
decimal Price);The gRPC contract generates its own types:
ProductReplyThese models serve different purposes.
REST models define an HTTP/JSON contract. Protobuf messages define a gRPC contract.
The domain model should remain independent from both:
Domain Model
/ \
/ \
REST DTO gRPC MessageThis separation prevents changes to one external contract from accidentally changing internal application behavior.
Keep Business Logic Out of the gRPC Service
The gRPC service should coordinate the request, not contain the entire business operation.
For example:
public sealed class CatalogService : Catalog.CatalogBase
{
private readonly IProductService _products;
public CatalogService(IProductService products)
{
_products = products;
}
public override async Task<ProductReply> GetProduct(
GetProductRequest request,
ServerCallContext context)
{
var product = await _products.GetAsync(
request.Id,
context.CancellationToken);
if (product is null)
{
throw new RpcException(
new Status(
StatusCode.NotFound,
"Product was not found."));
}
return new ProductReply
{
Id = product.Id,
Name = product.Name,
Price = (double)product.Price
};
}
}The gRPC service handles protocol-specific concerns while IProductService handles application logic.
This makes the business logic easier to test and reuse.
Handle Errors Using gRPC Status Codes
A REST API often communicates errors through HTTP status codes and JSON responses.
gRPC uses status codes.
For example:
throw new RpcException(
new Status(
StatusCode.InvalidArgument,
"Product ID must be greater than zero."));Common status codes include:
gRPC Status | Typical Use |
|---|---|
OK | Successful operation |
InvalidArgument | Invalid request data |
NotFound | Requested resource does not exist |
AlreadyExists | Resource already exists |
Unauthenticated | Authentication is missing or invalid |
PermissionDenied | Caller is authenticated but not authorized |
Unavailable | Temporary service or dependency failure |
DeadlineExceeded | Operation exceeded its allowed time |
Internal | Unexpected server-side failure |
Do not return Internal for every problem. Use meaningful status codes so clients can make appropriate decisions.
Pass Cancellation Through the Application
gRPC supports cancellation through ServerCallContext.
Use the request cancellation token when calling downstream services.
var product = await _products.GetAsync(
request.Id,
context.CancellationToken);This matters when clients disconnect or cancel requests.
Without cancellation propagation, the server may continue doing database or network work after the client has already stopped waiting for the result.
For long-running operations, cancellation should be passed through every layer that supports it.
Configure Deadlines
A client can specify a deadline for a gRPC operation.
Server-side code can inspect the deadline through the call context:
if (context.Deadline < DateTime.UtcNow)
{
throw new RpcException(
new Status(
StatusCode.DeadlineExceeded,
"The request deadline has expired."));
}In practice, application code should normally rely on the gRPC infrastructure and cancellation token rather than manually implementing deadline logic everywhere.
The important design principle is that service calls should have reasonable time limits.
A request that can wait indefinitely can eventually consume threads, connections, database resources, or other infrastructure.
Secure gRPC Endpoints
Authentication should be applied to gRPC services just as it is to REST APIs.
For JWT authentication:
Join the conversation! Your thoughts help the community grow.