0

I am trying to upload a form ( few fields along with multiple files attachments ) from angular 8 application to .NET core (CORS Enabled). POST API in .net core is accessible from angular when we send no files and without "Multipart/Form-data" content type, In this case fields are available but not files.

If I change the Content-Type to "Multipart/Form-data" and attach the files in formdata angular gives CORS issue. Below is my code :

Angular:

const formData = new FormData();
const options = {
         headers: new HttpHeaders({
             'Content-Type': 'multipart/form-data',
             'Access-Control-Allow-Origin' :'*'
         })
     }
this.selectedFiles.forEach((f) => formData.append('files', f));}
formData.append('Name',"Test");
this.http.post(url,formData,options).subscribe();

.NET Core:

[HttpPost]
        
        public object UploadData([FromForm] FormModel formModel)
        {
// save files and insert data in DB
}
user684805
  • 163
  • 2
  • 8
  • 1
    Does this answer your question? [How to enable CORS in ASP.net Core WebAPI](https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi) – Connor Low Sep 21 '21 at 15:15
  • 1
    A cors error can be misleading. If post requests work in general, it might actually be some other exception thrown in the web api. Do you have the option to debug the request in the web api? – Gunnar B. Sep 21 '21 at 16:45
  • @ConnorLow, I tried the methods mentioned in the link for me Cors was added after mvc, I changed it but still no luck. It is giving me error with multipart/form-data. – user684805 Sep 21 '21 at 18:30
  • It worked by removing the content type which I was setting manually, Adding Cors before Mvc as mentioned in the link shared by @ConnorLow and then sent the formData in body. – user684805 Sep 21 '21 at 19:20
  • Hi @user684805, please share your Startup.cs in asp.net core to let us know. Also please share the whole error message to us. – Rena Sep 22 '21 at 01:27

0 Answers0