-1

Following the Telerik walkthrough here to create a Telerik Report host.

In the .NET CORE 5 project I enable CORS as follows:

In Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers().AddNewtonsoftJson();
        services.AddRazorPages();

        // Configure dependencies for ReportsController.
        services.TryAddSingleton<IReportServiceConfiguration>(sp =>
        new ReportServiceConfiguration
        {
            //ReportingEngineConfiguration = ConfigurationHelper.ResolveConfiguration(sp.GetService<IWebHostEnvironment>()),
            ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
            HostAppId = "Net5RestServiceWithCors",
            Storage = new FileStorage(),
            ReportSourceResolver = new UriReportSourceResolver(
                System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
        });

        services.AddCors(corsOption => corsOption.AddPolicy(
          "ReportingRestPolicy",
          corsBuilder =>
          {
              corsBuilder.WithOrigins("*")
                .AllowAnyMethod()
                .AllowAnyHeader();
              //corsBuilder.AllowAnyOrigin()
              //  .AllowAnyMethod()
              //  .AllowAnyHeader();
          }
        ));

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseCors("ReportingRestPolicy");

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });

        

    }

The launchSettings.cs are as follows:

"iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:65271",
      "sslPort": 44398
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MyReportServer": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

To test I run the project and change the URL to https://localhost:44398/api/reports/version and I receive the correct response "16.1.22.511".

Then I open a new web browser and navigate to to https://localhost:44398/api/reports/version and get the same valid response.

In my front end project I set the report url as:

var reporturi = "https://localhost:44398/api/reports"

When the report viewer begins the report retrieval process it first calls the report version endpoint and I receive a CORS error in the report viewer.

Cannot access the Reporting REST service. (serviceUrl = 'https://localhost:44398/api/reports'). Make sure the service address is correct and enable CORS if needed. (https://enable-cors.org)

Running Chrome I inspect the F12 Network tab I see a Name of "version" and a Status of "CORS error".

Inspecting the Headers:

General
    Request URL: https://localhost:44398/api/reports/version
    Request Method: GET
    Status Code: 200 
    Referrer Policy: strict-origin-when-cross-origin

Response Headers
    access-control-allow-origin: *
    content-type: application/json; charset=utf-8
    date: Mon, 30 May 2022 14:10:10 GMT
    server: Microsoft-IIS/10.0
    x-powered-by: ASP.NET

Request Headers
    :authority: localhost:44398
    :method: GET
    :path: /api/reports/version
    :scheme: https
    accept: application/json, text/javascript, */*; q=0.01
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9
    origin: http://localhost:1202
    referer: http://localhost:1202/
    sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"
    sec-ch-ua-mobile: ?0
    sec-ch-ua-platform: "Windows"
    sec-fetch-dest: empty
    sec-fetch-mode: cors
    sec-fetch-site: cross-site
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

Based on this it appears that the endpoint is valid and the server's access-control-allow-origin is allowing all.

I modified the server to specifically allow http://localhost:1202 as well with the same result.

              corsBuilder.WithOrigins("http://localhost:1202")
                .AllowAnyMethod()
                .AllowAnyHeader();

I also tried the AlowAnyOrigin method:

              corsBuilder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();

I am enabling CORS in Startup.cs Configue between app.UseRouting(); and app.UseEndpoints() as is recommended.

The Status Code is 200 for the request which is Success and this may be normal even if a CORS error occurs, I'm not sure.

What can I try to resolve this CORS error?

kpg
  • 589
  • 6
  • 28

1 Answers1

0

From How to enable CORS in ASP.net Core WebAPI

I needed to add AllowCredentials().

In working through this I made several adjustments to my original code. I moved all CORS statements to the top of the statup.cs methods and I changed the policy-based CORS setup to the simpler non-policy syntax, but what got it to work was the addition of AllowCredentials().

Note to use AllowCredentials() you cannot also use AllAnyOrigin(), you must instead use WithOrigins() and specify each.

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors();

        services.AddControllers().AddNewtonsoftJson();
        services.AddRazorPages();

        // Configure dependencies for ReportsController.
        services.TryAddSingleton<IReportServiceConfiguration>(sp =>
        new ReportServiceConfiguration
        {
            ReportingEngineConfiguration = sp.GetService<IConfiguration>(),
            HostAppId = "Net5RestServiceWithCors",
            Storage = new FileStorage(),
            ReportSourceResolver = new UriReportSourceResolver(
                System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
        });

    }

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

        app.UseCors(
               options => options.WithOrigins("http://localhost:1202").AllowAnyMethod().AllowAnyHeader().AllowCredentials()
           );

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });

        

    }

Honestly I don't know why this needs to be so difficult, just saying.

kpg
  • 589
  • 6
  • 28