Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Core CORS works with GET but not wit POST

I am using Angular 4 app with Asp core web api which I test on the locahost with different ports. My WebApi requires Windows Authentication(need to get logon user name). All calls using GET work, but unfortunately, I cannot get POST to work. I have WebApi setup for CORS:

        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        services.AddDbContext<CatalogContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials();
            });

        });
        services.AddMvc();
    }

And angular 4 client is trying to post file

fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
  let file: File = fileList[0];
  let formData: FormData = new FormData();
  formData.append('uploadFile', file, file.name);
  let headers = new Headers();
  /** No need to include Content-Type in Angular 4 */
  headers.append('Content-Type', 'multipart/form-data');
  headers.append('Accept', 'application/json');

  let options = new RequestOptions({ headers: headers, withCredentials: true });
  this.http.post("http://localhost:495/api//upload",formData, options)
    .map(res => res.json())
    .catch(error => Observable.throw(error))
    .subscribe(
    data => console.log('success'),
    error => console.log(error)
    )
}

My error:

XMLHttpRequest cannot load http://localhost:495/api//upload. 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.

And Response headers

Content-Length:0 Date:Sun, 13 Aug 2017 13:13:09 GMT Persistent-Auth:true Server:Kestrel X-Powered-By:ASP.NET X-SourceFiles:=?UTF-8?B?QzpcU291cmNlIENvZGVcUGFydG5lcnNoaXBDYXRhbG9nXFBhcnRuZXJzaGlwQ2F0YWxvZ1xQYXJ0bmVyc2hpcENhdGFsb2cuV2ViQXBpXGFwaVx1cGxvYWQ=?=

Any help would be appreciated!

like image 398
Tom Brzeski Avatar asked Aug 13 '17 13:08

Tom Brzeski


People also ask

How do I allow cross origin requests in asp net core?

There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.


2 Answers

You need something like this:

services.AddCors(options =>
      {
        options.AddPolicy("CorsPolicy",
            builder => 
            builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .WithExposedHeaders("content-disposition")
            .AllowAnyHeader()
            .AllowCredentials()
            .SetPreflightMaxAge(TimeSpan.FromSeconds(3600)));
      });

Notice AllowCredentials().

You also need, in your Startup file Configure method:

app.UseCors("CorsPolicy");
like image 138
dee zg Avatar answered Oct 20 '22 17:10

dee zg


I stumbled upon this thread because I had the exact same thing. After many frustrating hours playing with the CORS settings, I noticed the POST did work but only when using https instead of http.

Maybe this can help someone.

like image 23
Henri De Roeck Avatar answered Oct 20 '22 16:10

Henri De Roeck