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!
There are three ways to enable CORS: In middleware using a named policy or default policy. Using endpoint routing. With the [EnableCors] attribute.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With