'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!
Solution 1:[1]
Preflight requests (OPTIONS) do not send auth info to server. So, you need to enable Anonymous Auth in addition to WinAuth. Please see: https://stackoverflow.com/a/50354772/946773
Solution 2:[2]
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");
Solution 3:[3]
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.
Solution 4:[4]
In my case I had to slighlty modified POST/Put method
From
public IHttpActionResult PostTest(Test objTest)
To
public IHttpActionResult PostTest([FromBody]Test objTest)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jaymjarri |
| Solution 2 | dee zg |
| Solution 3 | Henri De Roeck |
| Solution 4 | KumarHarsh |
