1

I am trying to enable CORS in Startup.cs with no luck. I have an Angular app on port 4200 trying to communicate with my c# Web app. I keep getting this error in Angular

Failed to load http://localhost:52008/Account/GetJWT: Response for preflight does not have HTTP ok status.

My research seems to indicate CORS is not being enabled properly. Any idea what I'm missing?

public void ConfigureServices(IServiceCollection services)
{
.....
    services.AddCors(options =>
    {
        options.AddPolicy("EnableCORS", builder =>
        {
            builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()
            .Build();
        });
    });
    .........
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.......
 app.UseCors("EnableCORS");
 ........
 }

And heres the Angular POST request:

  login(form: NgForm) {
    let credentials = JSON.stringify(form.value);
    console.log(credentials);
    this.http.post("http://localhost:52008/Account/GetJWT", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    })
  }

Result of POSTMAN query

enter image description here

Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • seems the `AllowCredentials` causes issue on `OPTIONS` verb, [see this QA](https://stackoverflow.com/a/52048304/4648586). looks like better to have the `[EnableCors("EnableCORS")]` into the controller than the globally registered for every request. and it will be best if you could use postman to see the headers.. – Bagus Tesa Sep 13 '18 at 23:47
  • or the `app.UseCors("EnableCORS");` was called after `app.UseMvc()`.. – Bagus Tesa Sep 13 '18 at 23:55
  • Please have a look at [Fiddler Proxy](https://www.telerik.com/fiddler), get familiar with it and use it often - it will tell you exactly what is going on with _all_ your requests and responses, and as an API/full stack developer you'll save hours upon hours dealing with issues like this. Find out what the HTTP status is to the preflight request and you'll be in a much better position to work out how to fix it. – pcdev Sep 14 '18 at 01:06
  • Windows authentication? Use IIS CORS module instead, https://learn.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference – Lex Li Sep 14 '18 at 01:34
  • @BagusTesa Is the image above what you meant by seeing the headers in Postman? And I checked- `app.UseCors("EnableCORS");` was called before app.UseMvc() – Rilcon42 Sep 14 '18 at 03:15
  • @Rilcon42 Do you have `[EnableCors("EnableCORS")]` added at the controller class or action method? Applying at controller class level will enable cors for all action methods – Mohsin Mehmood Sep 16 '18 at 20:30

4 Answers4

0
     public void ConfigureServices(IServiceCollection services)
        {
           //add cors service
            services.AddCors(options => options.AddPolicy("Cors",
                builder => {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                } ));

            services.AddMvc(); // 

//--------------------------------------

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.




 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors("Cors");//------>let app use new service
        app.UseMvc();

    }

Inside your controller make sure your grabbing the object from the body

//post req

 [HttpPost]
    public Message Post([FromBody] Message message)
    {

    var msg = new Message { Owner = message.Owner, Text = message.Text };
    db.Messages.AddAsync(msg);
    db.SaveChangesAsync();

    return message;

}
Mohamoud Mohamed
  • 515
  • 7
  • 16
0

You could configure the cores in startup.cs like below and add the origin to ConfigurationServices like below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowSpecificOrigin",
            builder => builder.WithOrigins("http://example.com"));
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Shows UseCors with named policy.
    app.UseCors("AllowSpecificOrigin");

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

Add the CORS policy to the specific action.

[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Reference : Enable Cross-Origin Requests (CORS) in ASP.NET Core

Ravikumar
  • 613
  • 1
  • 9
  • 22
0

Use the following code to enable CORS. .NET Core version: 2.1 and angular version: 1.6.7

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.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddJsonOptions(options =>
        {
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;                
        });

        services.AddCors();
    }

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

        app.UseMvc();
    }   
}

Angular Code:

$http.post("http://localhost:52008/Account/GetJWT", credentials,{
    headers: new HttpHeaders({
        "Content-Type": "application/json"
})).then(
function(response) {
    console.log(response);
},
function() {
    console.log("unable to login");
});

Let me know if problems still persists.

Gopi
  • 1,311
  • 1
  • 10
  • 8
0

change to your web.config:

<system.webServer>

    ...

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
</httpProtocol>
</system.webServer>
Rohit Dhiman
  • 2,691
  • 18
  • 33