0

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

Apeksha
  • 485
  • 6
  • 23

3 Answers3

0

As it says in the error when you remove the Content-Type header:

Access to XMLHttpRequest at 'http://server' from origin 'http://localhost' has been blocked by CORS policy

favdev
  • 99
  • 5
0

I switched to using the Ionic native http plugin as a solution. Which is not the end of my problems, though. See this question for more info.

Apeksha
  • 485
  • 6
  • 23
  • I honestly would recommend you keep trying to use Angular Http Client. Its is faster and more powerful. Once you figure out the issue, whether on server or client side everything will work smoother. – Stephen Romero May 16 '19 at 17:01
  • @StephenRomero I read that the native plugin prevents the browser CORS issue and I saw that as a benefit in my case. Is there a good comparison for the features, speed, etc for both plugins that could help me choose? – Apeksha May 21 '19 at 14:58
  • 1
    Well from my experience from research, the Angular plugin is more efficient. If you plan on using Angular with your Ionic app, it will be more beneficial in the long run. I use PHP as my backend and had trouble with the CORS headers at first, but once I got the issue resolved everything worked beautifully. There are also alot more features with Angular http than Ionic. – Stephen Romero May 21 '19 at 15:02
0

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.

Apeksha
  • 485
  • 6
  • 23