This article shows how ASP.NET Core Razor Pages can be run in the same application as a gRPC service.

Code: https://github.com/damienbod/Secure_gRpc

Posts in this series

History

2019-12-17: Updated Nuget packages, .NET Core 3.1, updated grpc implementations

2019-09-06: Updated Nuget packages, .NET Core 3 preview 9

2019-08-13: Updated Nuget packages, .NET Core 3 preview 8

2019-07-28: Updated Nuget packages, .NET Core 3 preview 7

Adding Razor Pages to an existing gRPC service

This demo is built using the code created in the previous post, which is pretty much the gRPC code created from the ASP.NET Core 3.0 templates.

To support both Razor Pages and gRPC services hosted using a single Kestrel server, both HTTP and HTTP2 needs to be supported. This is done in the Program class of the application using a ConfigureKestrel method. Set the Protocols property to HttpProtocols.Http1AndHttp2.

public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>() .ConfigureKestrel(options => { options.Limits.MinRequestBodyDataRate = null; options.ListenLocalhost(50051, listenOptions => { listenOptions.UseHttps("server.pfx", "1111"); listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); }); });

Now we need to add the MVC middleware and also the Newtonsoft JSON Nuget package ( Microsoft.AspNetCore.Mvc.NewtonsoftJson ) as this is no longer in the default Nuget packages in ASP.NET Core 3.0. You need to add the Nuget package to the project.

Then add the MVC middleware.

public void ConfigureServices(IServiceCollection services) { ... services.AddGrpc(options => { options.EnableDetailedErrors = true; }); services.AddMvc() .AddNewtonsoftJson(); }

In the configure method, the static files middleware need to be added so that the css and the Javascript will be supported. The Razor Pages are then added to the routing.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... app.UseStaticFiles(); app.UseRouting(routes => { routes.MapGrpcService<GreeterService>(); routes.MapRazorPages(); }); }

Add the Razor Pages to the application and also the css, Javascript files inside the wwwroot.

And now both application types are running, hosted on Kestrel in the same APP which is really cool.

Links:

https://github.com/grpc/grpc-dotnet/

https://grpc.io/