I have a .Net/C# Web API 2.0 REST service which works fine if test with Postman, but always get null parameter if call from Angular2/4 http service with Post.
below is the code:
C#:
public class UsersController : ApiController
{
// POST: api/users/login
public string login([FromBody]string value)
{
var ss = value;
return value;
}
}
Angular2 service:
login(email: string, password: string) {
const headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
const theBody = {'email': email, 'password': password};
const requestoptions: RequestOptions = new RequestOptions({
method: RequestMethod.Post,
url: this.host + '/users/login',
headers: headers,
body: JSON.stringify(theBody)
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
return res.json;
})
.catch(this.logAndPassOn);
}
When test with Postman, I set header as Content-Type : application/json, and body select "raw".
everything looks the same, however the Angular2 Http Post service doesn't work anyway, I always get null value.
Thanks in advance for any any help.
Remove JSON.stringify
: There's no need to convert it to a string.
On the Web Api side, you'll be better off with a POCO for the incoming data. Create a class that includes two string properties, eg:
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
}
Then, change [FromBody]string value
to [FromBody]LoginViewModel viewModel
.
To try and clarify a little more, there's a big difference between this:
{
"email": "some-email",
"password": "some-password"
}
and this:
"{ email: 'some-email', password: 'some-password' }"
The first example is a JSON object, whereas the second is just a string and nothing more. It doesn't matter that the data inside looks like JSON: it isn't. In your Postman example, you were actually sending a string, but perhaps Angular is being a bit clever and basically ignoring your JSON.stringify
in the first place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.