상세 컨텐츠

본문 제목

Add CORS To gRPC-Web Server - C# & .NET

본문

If you separate front and back end, you may have CORS issue.  The CORS issue can happen if you assign different ports or use different domain.
 

반응형

This example shows how to add CORS to open a service to ALL external addresses to simplify the code.  In any production environment, this is NOT a safe option.  You must use CORS policy to allow only certain number of external addresses.
 
Before starting this, please make sure that you have gRPC-Web server feature already added to your gRPC service project. 
 

728x90

 
Add the following lines of codes to Program.cs file.

builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
    builder.AllowAnyOrigin() //this is where it opens to ALL origin.  You must use WithOrigin() in a production enviroment
           .AllowAnyMethod()
           .AllowAnyHeader()
           .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
}));

Then add the following lines of codes (in the app section of Program.cs):

app.UseRouting();
app.UseGrpcWeb(); 
// Add the following line BELOW UseGrpcWeb()
app.UseCors();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGrpcService<GreeterService>()
        .EnableGrpcWeb()
        // You are adding this line. "AllowAll" is the name of CORS policy you configured above
        .RequireCors("AllowAll");
});

Congrats!  You are all set.


 

728x90
반응형

관련글 더보기