Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
4 contributors

Users who have contributed to this file

@Rick-Anderson @JunTaoLuo @nschonni @JamesNK
81 lines (51 sloc) 3.22 KB
title author description monikerRange ms.author ms.date uid
gRPC services with ASP.NET Core
juntaoluo
Learn the basic concepts when writing gRPC services with ASP.NET Core.
>= aspnetcore-3.0
johluo
03/08/2019
grpc/aspnetcore

gRPC services with ASP.NET Core

This document shows how to get started with gRPC services using ASP.NET Core.

[!INCLUDE]

Get started with gRPC service in ASP.NET Core

View or download sample code (how to download).

Visual Studio

See Get started with gRPC services for detailed instructions on how to create a gRPC project.

Visual Studio Code / Visual Studio for Mac

Run dotnet new grpc -o GrpcGreeter from the command line.


Add gRPC services to an ASP.NET Core app

gRPC requires the following packages:

Configure gRPC

gRPC is enabled with the AddGrpc method:

[!code-cs]

Each gRPC service is added to the routing pipeline through the MapGrpcService method:

[!code-cs]

ASP.NET Core middlewares and features share the routing pipeline, therefore an app can be configured to serve additional request handlers. The additional request handlers, such as MVC controllers, work in parallel with the configured gRPC services.

Integration with ASP.NET Core APIs

gRPC services have full access to the ASP.NET Core features such as Dependency Injection (DI) and Logging. For example, the service implementation can resolve a logger service from the DI container via the constructor:

public class GreeterService : Greeter.GreeterBase
{
    public GreeterService(ILogger<GreeterService> logger)
    {
    }
}

By default, the gRPC service implementation can resolve other DI services with any lifetime (Singleton, Scoped, or Transient).

Resolve HttpContext in gRPC methods

The gRPC API provides access to some HTTP/2 message data, such as the method, host, header, and trailers. Access is through the ServerCallContext argument passed to each gRPC method:

[!code-cs]

ServerCallContext does not provide full access to HttpContext in all ASP.NET APIs. The GetHttpContext extension method provides full access to the HttpContext representing the underlying HTTP/2 message in ASP.NET APIs:

[!code-cs]

Additional resources

  • xref:tutorials/grpc/grpc-start
  • xref:grpc/index
  • xref:grpc/basics
  • xref:grpc/migration
You can’t perform that action at this time.