[英]Angular2/4 http POST services call .Net/MVC Web API 2.0 REST parameter is null
我有一個.Net / C#Web API 2.0 REST服務,如果使用Postman進行測試,則可以正常工作,但是如果使用Angular2 / 4 http服務進行調用,則總是獲取null參數。
下面是代碼:
C#:
public class UsersController : ApiController
{
// POST: api/users/login
public string login([FromBody]string value)
{
var ss = value;
return value;
}
}
Angular2服務:
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);
}
使用Postman進行測試時,我將標頭設置為Content-Type:application / json,正文選擇“ raw”。
一切看起來都一樣,但是Angular2 Http Post服務仍然無法正常工作,我總是得到null值。
預先感謝您的任何幫助。
刪除JSON.stringify
:無需將其轉換為字符串。
在Web Api方面,使用POCO處理傳入數據會更好。 創建一個包含兩個字符串屬性的類,例如:
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
}
然后,將[FromBody]string value
更改為[FromBody]LoginViewModel viewModel
。
為了進一步說明,這之間有很大的區別:
{
"email": "some-email",
"password": "some-password"
}
和這個:
"{ email: 'some-email', password: 'some-password' }"
第一個示例是JSON對象,而第二個示例只是一個字符串,僅此而已。 里面的數據看起來像JSON沒關系:不是。 在您的Postman示例中,您實際上是在發送一個字符串,但是Angular可能有點聰明,並且首先忽略了JSON.stringify
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.