0

I have ASP.NET Core API and application in Angular 5. I have added code in Startup.cs to enable cors and to allow all origin, but still, it is giving me an error that

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

Below is my web api code:

  public void ConfigureServices(IServiceCollection services)
    {
        WriteToFile("In configure service");
        try
        {
            // Enable Cors
            services.AddCors();
            services.AddMvc();
        }
        catch
        {
            WriteToFile("Not Connected in StartUP");
        }
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        try
        {
            app.UseCors(builder =>
               builder.AllowAnyOrigin()
               .AllowAnyHeader()
               .AllowAnyMethod());

            app.UseMvc();

            WriteToFile("After cors use In configure");

        }
        catch(Exception ex)
        {
            WriteToFile("Error in  configure"+ex.Message);
        }
    }
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Roshan04
  • 31
  • 8
  • 1
    It will give you that error, if saying a service can not be injected. Try to look more clearly is that error is exactly about CORS – Suren Srapyan Mar 24 '18 at 17:29
  • Sorry i am new to angular and web api , but how to find the root cause – Roshan04 Mar 24 '18 at 17:32
  • Remote the constructor params from that controller to which you navigate first and check if it goes into the constructor – Suren Srapyan Mar 24 '18 at 17:34
  • No Its not giving in that controller constructor, but still i am not sure why it is like this. can you please help me – Roshan04 Mar 24 '18 at 17:53
  • @Roshan04 do you send [credentials](https://learn.microsoft.com/en-us/aspnet/core/security/cors#credentials-in-cross-origin-requests) with a request? – Set Mar 24 '18 at 22:35
  • Yes I use token – Roshan04 Mar 24 '18 at 22:37
  • I http post request I am sending username and password. – Roshan04 Mar 25 '18 at 05:21
  • 2
    There is a server error, is not related to CORS. – alsami Mar 26 '18 at 11:46
  • You can resolve the same in the following way that I already posted a solution here, how to make CORS working: https://stackoverflow.com/questions/49207455/cant-get-cors-working-for-asp-net-core-web-api?answertab=active#tab-top – Jayoti Parkash Mar 16 '19 at 06:51

1 Answers1

0

Hey I think you should put

[EnableCors(origins: "**http:/...(Here the website you want to enter)**", headers: "*", methods: "*")] 

just before the class in your Controller.

Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52