[英]Angular post request to c# web api 2 RESTful web service
我正在嘗試將來自角度客戶端的http發布請求發送到C#Web API 2 RESTful Web服務。
我的客戶:
var userId = "123456";
var password = "654321";
const headersContent = new Headers().set('Content-Type', 'application/x-www-form-urlencoded');
var url = "http://localhost:35615/login"
this.http.post(url, {
"userId": userId,
"password": password
}, {withCredentials: true}).subscribe(res => {
console.log(res);
});
我的服務器:
[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] string parameters)
{
//Deserialize the parameters.
}
我的問題是參數var為null,盡管chrome的網絡標簽中的發布請求包含了數據。
有人可以向我解釋我在做什么錯嗎,我該如何解決? 謝謝!
您正在傳遞具有屬性“ UserId”和“ Password”的匿名對象。 制作一個具有這兩個屬性的數據協定類作為字符串,並在REST方法的參數中使用它。
public IHttpActionResult LoginReq([FromBody] User user) { ... }
如果要從Angular POST請求傳遞對象,則可以將Web API POST方法更改為接受用戶定義的類型作為參數,以從請求正文中讀取它。
您可以在C#中創建以下用戶定義的類型,以綁定來自角度發布請求的UserId和Password屬性
public class UserLogin
{
public int UserId { get; set; }
public string Password { get; set; }
}
[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] UserLogin user)
{
//Deserialize the parameters.
}
我建議閱讀本文檔,以了解有關Web API中參數綁定的更多信息。 相信我,值得您花時間。
您發布了userId
和password
,但是需要String parameters
。 更改為String userId
和String password
。 Modelbinder僅將綁定匹配屬性。
只需添加JSON.stringify()
您JSON.stringify()
一個對象發送到服務器,該對象只需要一個字符串作為參數,因此將其作為字符串並傳遞值,否則在服務器端創建一個帶有userid
和password
的模型並提及該對象
let obj = {
"userId": userId,
"password": password
};
this.http.post(url, JSON.stringify(obj), {withCredentials: true}).subscribe(res => {
console.log(res);
});
上面的代碼將使用string parameters
-繼續嘗試使用模型並從Angular傳遞對象
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.