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

I am using an Angular 4 application with the basic Asp web interface, which I am testing on locahost with different ports. My WebApi requires Windows authentication (you need to get the login name of the system). All calls using GET work, but unfortunately I cannot get POST to work. I have a WebApi setting 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 tries to send the 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 mistake:

XMLHttpRequest cannot load http: // localhost: 495 / api // upload . The requested resource does not have an Access-Control-Allow-Origin header. Origin ' http: // localhost: 4200 ' is therefore not allowed. The response was an HTTP status code of 500.

And the response headers

Content-Length: 0 Date: Sun, Aug 13, 2017 1:13:09 PM GMT Persistent-Auth: true Server: Kestrel X-Powered-By: ASP.NET X source code files: ??? = Utf-8 v

Any help would be appreciated!

+5
source share
1 answer

You need something like this:

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

Pay attention to AllowCredentials() .

You will also need in the Startup Configure file:

 app.UseCors("CorsPolicy"); 
0
source

Source: https://habr.com/ru/post/1270828/


All Articles