15

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");
5
  • 1
    Do your client-side Blazor share the same domain with the server ?
    – enet
    Commented Jul 22, 2019 at 10:02
  • What address are you making requests from Blazor to? What address your Blazor application located?
    – codevision
    Commented Jul 22, 2019 at 10:06
  • 1
    They indeed share the same domain. Commented Jul 22, 2019 at 10:17
  • 1
    If so, the issue is not with CORS. This is a user code problem.
    – enet
    Commented Jul 22, 2019 at 10:38
  • CORS headers are better returned by IIS, blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
    – Lex Li
    Commented May 22 at 16:31

5 Answers 5

2

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 !

1

you need to specify your policy name in the middleware.

builder.Services.AddCors(policy =>{

    policy.AddPolicy("Policy_Name", builder =>         
      builder.WithOrigins("https://*:5001/")
        .SetIsOriginAllowedToAllowWildcardSubdomains()
        .AllowAnyOrigin()
  
    
 );});

// Configure the HTTP request pipeline.

 app.UseCors("Policy_Name");
1

For me I was using app.UseCors() after app.MapControllers(). After fixing the order it worked.

0

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.

5
  • I have checked I am running from http. Commented Jul 24, 2019 at 8:54
  • Sorry, but I ask anyway, and you are positive that you do not make requests to HTTP and exact same port?
    – codevision
    Commented Jul 24, 2019 at 11:11
  • I am making request to the exact same port and the request is http not https.So my server is hosted on : 172.22.XX.YY:8600 and i make requests to that address. Commented Jul 25, 2019 at 8:14
  • Can you open Chrome web console, and try to make same request using fetch for example. Client Blazor just call fetch under the hood, so it will be fair troubleshooting.
    – codevision
    Commented Jul 30, 2019 at 15:57
  • I get the same error and it makes no sense. Surely the whole point of a client/server architecture is that the client and server can be in different places. Commented Jun 10, 2021 at 18:19
0

@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.

4
  • I am using .NET Core 2.1 for the server project Commented Jul 22, 2019 at 10:39
  • And why don't you upgrade ??? Show the code of the http request you make...show your Web Api... Show the Startup code...Help us to help you.
    – enet
    Commented Jul 22, 2019 at 11:29
  • See the New Update part in my answer
    – enet
    Commented Jul 22, 2019 at 13:58
  • I think i didn't understand the question regarding the domain.The place where the client will get called will not be on the computer where the application is deployed. Commented Jul 24, 2019 at 5:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.