I’m trying to add gRPC to an existing ASP.NET Core 7 project. It is an older code-base so its not using the modern WebApplication.CreateBuilder(args)
approach.
This is my Configure
method where I added MapGrpcService
and MapGrpcReflectionService
in the endpoint mapping configuration:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseOpenApi();
app.UseSwaggerUi3(c => {
c.OAuth2Client = new NSwag.AspNetCore.OAuth2ClientSettings() { ClientId = null, ClientSecret = null };
});
app.UseCors(c => {
c.AllowAnyOrigin();
c.AllowAnyMethod();
c.AllowAnyHeader();
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<StateStoreService>();
if (env.IsDevelopment())
endpoints.MapGrpcReflectionService();
endpoints.MapControllers();
});
}
If I try to hit the gRPC endpoint with Insomnia (REST/gRPC client GUI), I get the error message
13 Received RST_STREAM with code 2 triggered by internal client error: Protocol error
With the command line tool
./grpcurl -plaintext localhost:5010 data_provider_service.v1.StateStore/ReadStates
I get
Failed to dial target host "localhost:5010": context deadline exceeded
Interestingly, at some point the gRPC service was working (I think with the same code – it seems to behave somewhat non-deterministic), but then the regular HTTP requests did fail with a CORS error in the browser. I could not get both to work at the same time.
Question:
How do I need to configure my app, so that gRPC endpoints and my existing HTTP endpoints work at the same time?
Update:
It seems to be a problem caused by protocol mismatch. So let me give you some more context: I’m adding gRPC to a legacy app which offers an unsecured HTTP API. For backwards compatibility, this should not change to HTTPS. So I guess the question boils down to: How can my app provide an unsecured HTTP API (which apparently requires HTTP/1.1) and a gRPC API (which apparently requires HTTP/2) at the same time?
2
Answers
The solution was actually simple and obvious.
My ASP.NET Core application continues to listen for HTTP connections on the existing ports, so existing clients don't break.
In addition it listens on a new port for HTTPS connections. There it supports REST calls and gRPC calls from new clients.
It’s possible to have API for both HTPP 1.1 and gRPC, but it’s not likely be the same one, you’ll need build API for each of them.