11
votes

I am trying to send a request from a Blazor(client-side) client to a server and i keep getting this error:

Access to fetch at '[route]' (redirected from '[other route]') from origin '[origin route]' has been blocked by CORS policy: 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.

On the server i have already added the CORS extension in the pipeline to no avail:

Server Startup

public void ConfigureServices(IServiceCollection services) {
            services.AddCors();
            services.AddResponseCompression(options => {
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                {
                    MediaTypeNames.Application.Octet,
                    WasmMediaTypeNames.Application.Wasm,
                });
            });
}
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

            app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

            app.UseResponseCompression();

            app.UseMvc();

            app.UseBlazor<Client.Startup>();

        }

Blazor Client request

public async Task<Catalog> GetCatalogAsync() {
            try {
                HttpRequestMessage message = new HttpRequestMessage {
                    RequestUri = new Uri(BASE_PATH + Routes.GET_CATALOG), //BASE_PATH= 172.XX.XX.XX:8600
                    Method = HttpMethod.Get
                };
                var resp = await this.client.SendAsync(message); // client is HttpClient
                var resultString = await resp.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<Catalog>(resultString);
                return data;

            } catch (Exception ex) {

                throw;
            }

        }

Controller

[HttpGet]
[Route(Routes.GET_CATALOG)]
public async Task<Catalog> GetCatalogAsync() {
    try {
        var registry = await this.adminService.GetCatalogAsync();
        return registry;
    } catch (Exception ex) {

        throw;
    }
}

POCO

[Serializeable]
public struct Catalog{
}

What else can i do to be able to reach my server? Is it due to Blazor ? As you can see i have already added the UseCors(...).

P.S
I have published my Blazor Server project together with the Client.They are in the same directory.This folder i placed it on a computer,and i am trying from my computer to open blazor : 172.168.18.22:8600/

Update
I have also tried adding headers to my HttpRequestMessage to no avail:

HttpRequestMessage message = new HttpRequestMessage {
                    RequestUri = new Uri(BASE_PATH + Routes.GET_CATALOG),
                    Method = HttpMethod.Get,

                };
message.Headers.Add("Access-Control-Allow-Origin","*");
message.Headers.Add("Access-Control-Allow-Credentials", "true");
message.Headers.Add("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type");
3
Do your client-side Blazor share the same domain with the server ?enet
What address are you making requests from Blazor to? What address your Blazor application located?codevision
They indeed share the same domain.Bercovici Adrian
If so, the issue is not with CORS. This is a user code problem.enet

3 Answers

1
votes

@Bercovici Adrian, why do you add CORS support to your App ? Do you make cross origin requests ? If you don't, don't try to solve the issue by adding unnecessary configuration that may lead to more subtle bugs.

As usual, without seeing a repo of this app, can't help you any further.

Update:

What is this UseBlazor ?

You should upgrade your app to the latest version...

New Update:

Sorry, but I'm using the current preview version of Blazor

Startup class

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddNewtonsoftJson();
        services.AddResponseCompression(opts =>
        {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBlazorDebugging();
        }
        **// Instead of UseBlazor**
        app.UseClientSideBlazorFiles<Client.Startup>();
        app.UseStaticFiles();

        app.UseRouting();

        **// This configure your end points**
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
        });
    }
}

Note that I've removed the configuration of CORS as your client and server share the same domain. Please use the docs how to configure CORS appropriately.

Try this and see if it is working for you (I guess your issue is related to the configuration of the endpoints. Somehow, it seems to me that because you did not configure the endpoints, your request is redirected, and thus you get the message displayed by you above.)

Next to do is to check if your http request was appropriately cooked. But first checks the end points.

0
votes

Check that you do not send HTTP requests when running from HTTPS. For example if you send requests to http://172.168.18.22:8600 when your application was opened in https://172.168.18.22:8600 you may have an issue.

0
votes

Somehow the problem was due to a very old client version that was cached on the browser.Never again will i forget to clear the browser cache after this problem. Thank you all for your help and support !