question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

"No 'Access-Control-Allow-Origin'" call from custom domain with Blazor.NET WASM

See original GitHub issue

What version of gRPC and what language are you using?

gRPC v3 C#

What operating system (Linux, Windows,…) and version?

Linux Ubuntu 18.04 LTS Server hosted on Azure VM

What runtime / compiler are you using

Compiler on Local Machine: .NET Core SDK 3.1.302 Runtime on Server: AspNetCore 3.1.6

Blazor.NET WASM

Google.Protobuf v3.12.3 Grpc.Net.Client.Web v2.30.0 Grpc.Net.ClientFactory v2.30.0 Grpc.Tools v2.30.0

gRPC Service

Grpc.AspNetCore v2.30.0 Grpc.AspNetCore.Web v2.30.0

What did you do?

My Blazor.NET WebAssembly works fine calling grpc in my local machine (https://localhost:5001)

But when I call it from my domain (https://grpc.domain.com) it said:

Access to fetch at ‘https://grpc.blazor.hometemp.bidipeppercrap.com/character.Character/SearchCharacter’ from origin ‘https://localhost:44395’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

When I call with curl, the result is the same for localhost:5000 and http

I use Nginx to proxy pass localhost:5000 to my https domain (ssl configured with certbot)

When I use cURL

curl

Response header from the server (gRPC Service)

response header


Blazor.NET Configuration

        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            builder.Services.AddSingleton(services =>
            {
                var httpHandler = new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler());

                return GrpcChannel.ForAddress("https://grpc.blazor.hometemp.bidipeppercrap.com", new GrpcChannelOptions { HttpHandler = httpHandler });
            });

            await builder.Build().RunAsync();
        }

gRPC Service Configuration

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContextPool<SpellTestContext>(options => options
                .UseMySql(Configuration.GetConnectionString("SpellTestConnection")));

            services.AddGrpc();

            services.AddCors(o => o.AddPolicy("AllowAll", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding");
            }));
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseGrpcWeb();

            app.UseCors();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<CharacterService>().EnableGrpcWeb().RequireCors("AllowAll");

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
wrosenuancecommented, Jan 20, 2021

I had this error and found that I had to add “X-Grpc-Web” and “User-Agent” to the headers exposed to the application by the CORS policy.

services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
    builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithExposedHeaders("Grpc-Status", "Grpc-Message", "Grpc-Encoding", "Grpc-Accept-Encoding", "X-Grpc-Web", "User-Agent");
}));

I had started with the original poster’s code so I also had the RequireCors("AllowAll") call referencing the above policy after EnableGrpcWeb().

app.UseRouting();
app.UseGrpcWeb();
app.UseCors();

app.UseEndpoints(endpoints =>
{
  endpoints.MapGrpcService<CharacterService>().EnableGrpcWeb().RequireCors("AllowAll");

  // ...snip... 
});

This seemed to fix things for me! I hope it helps anyone else who winds up here when searching for this error.

0reactions
drodiccommented, Oct 18, 2020

I thought it was just part of the nginx.conf file 🙂. And what is localhost: 5000, is that grpc uri server or application uri from which you call grpc service?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Blazor Request blocked by CORS policy
Access to fetch at '[route]' (redirected from '[other route]') from origin '[origin route]' has been blocked by CORS policy: No 'Access-Control- ...
Read more >
Calling external API in C# Blazor WebAssembly
I used to have a local proxy on my local machine for debugging until I got around to fixing the CORS on an...
Read more >
How to Build a CORS Proxy for Client-side Blazor
The app was making a call to an API but from the client-side ... access control check: No 'Access-Control-Allow-Origin' header is present on ......
Read more >
Dealing with CORS issues : r/Blazor
So I am not an expert really on anything front end, but I've been giving blazor WASM a try. And immediately I am...
Read more >
Enable Cross-Origin Requests (CORS) in ASP.NET Core
This article shows how to enable CORS in an ASP.NET Core app. Browser security prevents a web page from making requests to a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found