AspNetCore.Docs/aspnetcore/grpc/index.md

260 lines
8.4 KiB
Markdown
Raw Normal View History

---
title: Introduction to gRPC on .NET
author: jamesnk
description: Learn about gRPC services with Kestrel server and the ASP.NET Core stack.
monikerRange: '>= aspnetcore-3.0'
ms.author: jamesnk
2021-10-05 02:15:42 +08:00
ms.date: 09/28/2021
no-loc: [Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
uid: grpc/index
---
# Introduction to gRPC on .NET
By [James Newton-King](https://twitter.com/jamesnk)
::: moniker range=">= aspnetcore-6.0"
2021-06-07 18:03:02 +08:00
[gRPC](https://grpc.io) is a language agnostic, high-performance Remote Procedure Call (RPC) framework.
The main benefits of gRPC are:
2019-10-02 08:55:21 +08:00
* Modern, high-performance, lightweight RPC framework.
* Contract-first API development, using Protocol Buffers by default, allowing for language agnostic implementations.
* Tooling available for many languages to generate strongly-typed servers and clients.
* Supports client, server, and bi-directional streaming calls.
* Reduced network usage with Protobuf binary serialization.
These benefits make gRPC ideal for:
* Lightweight microservices where efficiency is critical.
* Polyglot systems where multiple languages are required for development.
* Point-to-point real-time services that need to handle streaming requests or responses.
[!INCLUDE[](~/includes/gRPCazure.md)]
## C# Tooling support for .proto files
gRPC uses a contract-first approach to API development. Services and messages are defined in *\*.proto* files:
```protobuf
syntax = "proto3";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
```
.NET types for services, clients, and messages are automatically generated by including *\*.proto* files in a project:
* Add a package reference to [Grpc.Tools](https://www.nuget.org/packages/Grpc.Tools/) package.
* Add *\*.proto* files to the `<Protobuf>` item group.
```xml
<ItemGroup>
<Protobuf Include="Protos\greet.proto" />
</ItemGroup>
```
For more information on gRPC tooling support, see <xref:grpc/basics>.
## gRPC services on ASP.NET Core
gRPC services can be hosted on ASP.NET Core. Services have full integration with ASP.NET Core features such as logging, dependency injection (DI), authentication, and authorization.
### Add gRPC services to an ASP.NET Core app
gRPC requires the [Grpc.AspNetCore](https://www.nuget.org/packages/Grpc.AspNetCore) package. For information on configuring gRPC in a .NET app, see [Configure gRPC](xref:grpc/aspnetcore#configure-grpc).
### The gRPC service project template
2021-10-05 02:15:42 +08:00
The **ASP.NET Core gRPC Service** project template provides a starter service:
```csharp
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request,
ServerCallContext context)
{
_logger.LogInformation("Saying hello to {Name}", request.Name);
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
```
2021-10-05 02:15:42 +08:00
`GreeterService` inherits from the `GreeterBase` type, which is generated from the `Greeter` service in the *\*.proto* file. The service is made accessible to clients in *Program.cs*:
```csharp
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
```
To learn more about gRPC services on ASP.NET Core, see <xref:grpc/aspnetcore>.
## Call gRPC services with a .NET client
gRPC clients are concrete client types that are [generated from *\*.proto* files](xref:grpc/basics#generated-c-assets). The concrete gRPC client has methods that translate to the gRPC service in the *\*.proto* file.
```csharp
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
2020-02-13 04:43:37 +08:00
var response = await client.SayHelloAsync(
new HelloRequest { Name = "World" });
Console.WriteLine(response.Message);
```
A gRPC client is created using a channel, which represents a long-lived connection to a gRPC service. A channel can be created using `GrpcChannel.ForAddress`.
For more information on creating clients, and calling different service methods, see <xref:grpc/client>.
## Additional resources
* <xref:grpc/basics>
* <xref:grpc/aspnetcore>
* <xref:grpc/client>
* <xref:grpc/clientfactory>
* <xref:tutorials/grpc/grpc-start>
::: moniker-end
::: moniker range=">= aspnetcore-3.0 < aspnetcore-6.0"
[gRPC](https://grpc.io) is a language agnostic, high-performance Remote Procedure Call (RPC) framework.
The main benefits of gRPC are:
* Modern, high-performance, lightweight RPC framework.
* Contract-first API development, using Protocol Buffers by default, allowing for language agnostic implementations.
* Tooling available for many languages to generate strongly-typed servers and clients.
* Supports client, server, and bi-directional streaming calls.
* Reduced network usage with Protobuf binary serialization.
These benefits make gRPC ideal for:
* Lightweight microservices where efficiency is critical.
* Polyglot systems where multiple languages are required for development.
* Point-to-point real-time services that need to handle streaming requests or responses.
[!INCLUDE[](~/includes/gRPCazure.md)]
## C# Tooling support for .proto files
gRPC uses a contract-first approach to API development. Services and messages are defined in *\*.proto* files:
```protobuf
syntax = "proto3";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
```
.NET types for services, clients, and messages are automatically generated by including *\*.proto* files in a project:
* Add a package reference to [Grpc.Tools](https://www.nuget.org/packages/Grpc.Tools/) package.
* Add *\*.proto* files to the `<Protobuf>` item group.
```xml
<ItemGroup>
<Protobuf Include="Protos\greet.proto" />
</ItemGroup>
```
For more information on gRPC tooling support, see <xref:grpc/basics>.
## gRPC services on ASP.NET Core
gRPC services can be hosted on ASP.NET Core. Services have full integration with ASP.NET Core features such as logging, dependency injection (DI), authentication, and authorization.
### Add gRPC services to an ASP.NET Core app
gRPC requires the [Grpc.AspNetCore](https://www.nuget.org/packages/Grpc.AspNetCore) package. For information on configuring gRPC in a .NET app, see [Configure gRPC](xref:grpc/aspnetcore#configure-grpc).
### The gRPC service project template
The gRPC service project template provides a starter service:
```csharp
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request,
ServerCallContext context)
{
_logger.LogInformation("Saying hello to {Name}", request.Name);
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
```
`GreeterService` inherits from the `GreeterBase` type, which is generated from the `Greeter` service in the *\*.proto* file. The service is made accessible to clients in *Startup.cs*:
```csharp
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<GreeterService>();
});
```
To learn more about gRPC services on ASP.NET Core, see <xref:grpc/aspnetcore>.
## Call gRPC services with a .NET client
gRPC clients are concrete client types that are [generated from *\*.proto* files](xref:grpc/basics#generated-c-assets). The concrete gRPC client has methods that translate to the gRPC service in the *\*.proto* file.
```csharp
var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var response = await client.SayHelloAsync(
new HelloRequest { Name = "World" });
Console.WriteLine(response.Message);
```
A gRPC client is created using a channel, which represents a long-lived connection to a gRPC service. A channel can be created using `GrpcChannel.ForAddress`.
For more information on creating clients, and calling different service methods, see <xref:grpc/client>.
## Additional resources
* <xref:grpc/basics>
* <xref:grpc/aspnetcore>
* <xref:grpc/client>
* <xref:grpc/clientfactory>
* <xref:tutorials/grpc/grpc-start>
::: moniker-end