AspNetCore.Docs/aspnetcore/grpc/aspnetcore.md

6.0 KiB

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 09/03/2019 grpc/aspnetcore

gRPC services with ASP.NET Core

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

Prerequisites

Visual Studio

[!INCLUDE]

Visual Studio Code

[!INCLUDE]

Visual Studio for Mac

[!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 Grpc.AspNetCore package.

Configure gRPC

In Startup.cs:

  • gRPC is enabled with the AddGrpc method.
  • Each gRPC service is added to the routing pipeline through the MapGrpcService method.

[!code-csharp]

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.

Configure Kestrel

Kestrel gRPC endpoints:

  • Require HTTP/2.
  • Should be secured with HTTPS.

HTTP/2

gRPC requires HTTP/2. gRPC for ASP.NET Core validates HttpRequest.Protocol is HTTP/2.

Kestrel supports HTTP/2 on most modern operating systems. Kestrel endpoints are configured to support HTTP/1.1 and HTTP/2 connections by default.

HTTPS

Kestrel endpoints used for gRPC should be secured with HTTPS. In development, an HTTPS endpoint is automatically created at https://localhost:5001 when the ASP.NET Core development certificate is present. No configuration is required.

In production, HTTPS must be explicitly configured. In the following appsettings.json example, an HTTP/2 endpoint secured with HTTPS is provided:

{
  "Kestrel": {
    "Endpoints": {
      "HttpsDefaultCert": {
        "Url": "https://localhost:5001",
        "Protocols": "Http2"
      }
    },
    "Certificates": {
      "Default": {
        "Path": "<path to .pfx file>",
        "Password": "<certificate password>"
      }
    }
  }
}

Alternatively, Kestrel endpoints can be configured in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(options =>
            {
                // This endpoint will use HTTP/2 and HTTPS on port 5001.
                options.Listen(IPAddress.Any, 5001, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http2;
                    listenOptions.UseHttps("<path to .pfx file>", 
                        "<certificate password>");
                });
            });
            webBuilder.UseStartup<Startup>();
        });

When an HTTP/2 endpoint is configured without HTTPS, the endpoint's ListenOptions.Protocols must be set to HttpProtocols.Http2. HttpProtocols.Http1AndHttp2 can't be used because HTTPS is required to negotiate HTTP/2. Without HTTPS, all connections to the endpoint default to HTTP/1.1, and gRPC calls fail.

For more information on enabling HTTP/2 and HTTPS with Kestrel, see Kestrel endpoint configuration.

[!NOTE] macOS doesn't support ASP.NET Core gRPC with Transport Layer Security (TLS). Additional configuration is required to successfully run gRPC services on macOS. For more information, see Unable to start ASP.NET Core gRPC app on macOS.

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-csharp]

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-csharp]

Additional resources