Gaui
Gaui

Reputation: 8939

Posting string data to Web API with AngularJS results in null

I'm using AngularJS v1.2.25. When I post a payload data (string) to my Web API via POST I always get null. I tried it with Postman (REST client), then I get a string. I was wondering whether this is a bug, because the typeof variable is string.

Here's my HTTP request (using Fiddler) from Postman:

POST http://localhost:60858/logout HTTP/1.1
Host: localhost:60858
Connection: keep-alive
Content-Length: 90
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8,is;q=0.6
Cookie: ASP.NET_SessionId=wox5u5pt5k0ox2hkontz53q4; .ASPXANONYMOUS=2CsdBwYO0AEkAAAAOTg3MDRkMjQtZmE4OC00OTE3LWE2NWYtMDk4ODY4MzA0Y2ZlgxJyUfsE9kDSzQ5edZ4FaUrI1djayGn3QfiUK9J4Ko01

"Ge8KFyOASBV8EbbbKJFrj8vkfZy0BYQZmvGrksFTPtesPvIAMvonRyr0qXNJGM18QxROI6s+26L/z/uOhSbJYA=="

Here's my actual HTTP request (via $http in AngularJS):

POST http://localhost:60858/logout HTTP/1.1
Host: localhost:60858
Connection: keep-alive
Content-Length: 88
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:53998
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:53998/
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8,is;q=0.6

Ge8KFyOASBV8EbbbKJFrj8vkfZy0BYQZmvGrksFTPtesPvIAMvonRyr0qXNJGM18QxROI6s+26L/z/uOhSbJYA==

Code where I'm using the $http method:

return $http[method](fullpath, data);

Code where I'm receiving the payload (string) in the Web API:

[Route("logout")]
[HttpPost]
public bool Logout([FromBody] string accessToken)
{
    var logout = _userService.LogUserOut(accessToken);
    return logout;
}

Upvotes: 1

Views: 337

Answers (1)

Gaui
Gaui

Reputation: 8939

Adding quotes "" around the data string works.

if(typeof data === 'string') data = '"' + data + '"';

Upvotes: 2

Related Questions