I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error:
XMLHttpRequest cannot load http://localhost:20377/api/posts. 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.
I am unsure why it works with application/json but not with multipart/form-data. Here's the code: Policy setup in Startup.cs
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
Angular method:
public createPost(title: string, body: string, file:File) {
const token = this.authService.getToken();
let formData: FormData = new FormData();
formData.append('File', file, file.name);
formData.append('Title', title);
formData.append('Body', body);
console.log(formData);
return this.http.post('http://localhost:20377/api/posts', formData,
{headers: new Headers({'Content-Type': 'multipart/form-data'})})
.map(res => {
console.log(res);
});
Web API core controller:
[EnableCors("CorsPolicy")]
[HttpPost]
public IActionResult CreatePost([FromBody] PostCreate model)
{
return Ok(model.Body);
}