-1

I am trying to establish the connection between Angular and my .net API using Cors. I keep getting this error :

localhost/:1 Access to XMLHttpRequest at 'https://localhost:44378/api/OffRec' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In order to fix this error. I added the addCors in my ConfigureServices and userCors in Configure like so:

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin");
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.AddControllers();
               services.AddDbContext<db_recloadContext>();
        }

My Configure method just useCors:

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

            }
            else
            {
                app.UseHsts();
            }
            app.UseRouting();
            app.UseCors("CorsPolicy");
           app.UseHttpsRedirection();

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

My api has a very simple code that returns a string and when I run my api, it works fine.

I have been struggling with this error for past 2 days. Any hint or help will be highly appreciated.

This is what I tried based on the answer below Still getting the same error:

 services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin:*");
                });
            });

below is the image of the error:

enter image description here

below is my api:

namespace RecLoad.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAnyCorsPolicy")]

   [HttpGet]
       public ActionResult<string> Get()
        {

            return "This is a test";

        }
rimi
  • 624
  • 5
  • 15

1 Answers1

0

CORS is a facility that lets the owner of some service restrict where that service may be accessed from. You have a website at localhost:4200, and it is contacting a web service at localhost:44378 to request some data. I know these are both localhost but they're different things; they might as well be a script on http://mysite.example trying to get data from http://remoteservice.example.

So, your browser, running the script on the page at the 4200 site, knows it is contacting a server that is different to the one it downloaded the script from, so it says to that other server "hey, tell me what servers you'll accept requests from, for that resource at /api/offRec" and the server (at 44378) responds with something like "I'll allow only scripts that were downloaded from me"

At this point your browser halts the request; the "foreign" server has not said it is willing to serve that resource to your script

What you need to do, as the admin of the 44378 server, is to add some CORS headers to its configuration saying either "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: https://localhost:4200" etc, so that when the browser running the script on the site at port 4200 asks for info from the 44378 resource, the response it gets also contains a header that permits the access


Just to reiterate, in case I wasn't totally clear on it: it is the server running the 44378 site that has to add the headers, NOT the 4200 site

Use a web browser to make a request to the 44378 site and look at the headers in a dev tools inspector. If you don't see an Access-Control-Allow-Origin header, reconfigure it 'til you do

Caius Jard
  • 72,509
  • 5
  • 49
  • 80