I am trying to do something very basic in my Ionic4 app - post data to an Asp.Net Web API 2 interface. The request is successful, but there is no data received on the server.
import { HttpClient } from '@angular/common/http';
someAction(assetId: number) {
let asset = new FormData();
asset.append("assetId", assetId.toString());
asset.append("UserId", "1");
return this.httpClient.post(this.url + "SomeAction", asset, { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).toPromise();
}
On the server (C#):
[HttpPost]
[Route("Service/SomeAction")]
public HttpResponseMessage SomeAction(AccessData asset)
{
return new HttpResponseMessage(_service.LogAsset(asset));
}
The asset
object on the server is instantiated, but does not contain values sent by the client.
Also, removing/changing the headers sent results in request failing completely.
Edit: Removing the header results in error 404, and also has this in the console:
Access to XMLHttpRequest at 'http://server' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Changing the header to "multipart/form-data" results in error 415 - unsupported media type
Edit #2: This works with Postman and HTTPBot (iPhone), just not from my Ionic app
UPDATE: I eventually fixed the issue by enabling CORS. I had enabled CORS in web.config
and expected it to suffice, but it turns out I actually needed to install the Microsoft.AspNet.WebApi.Cors
package and add the [EnableCors]
attribute to my post methods.