2017-02-16 68 views
11

我有一個新的API,我用Asp.Net Core構建,並且我無法獲得發佈到端點的任何數據。Asp.Net核心帖子FromBody Always Null

這裏的終點是什麼樣子:

[HttpPost] 
[Route("StudentResults")] 
public async Task<IActionResult> GetStudentResults([FromBody]List<string> userSocs, [FromBody]int collegeId) 
{ 
    var college = await _collegeService.GetCollegeByID(collegeId); 
    // var occupations = await _laborMarketService.GetOccupationProgramsBySocsAndCollege(userSocs, college); 
    return Ok(); 
} 

這裏就是我的有效載荷我通過郵遞員送的樣子:

{ 
    "userSocs": [ 
      "291123", 
      "291171", 
      "312021", 
      "291071", 
      "152031", 
      "533011" 
     ], 
    "collegeId": 1 
} 

我要確保我有郵遞員設置爲POST,使用content-type = application/json。我在做什麼錯>?

回答

20

您總是會得到null,因爲您需要將所有後置變量封裝在一個對象中。就像這樣:

public class MyPostModel { 
    public List<string> userSocs {get; set;} 
    public int collegeId {get; set;} 
} 

然後

public async Task<IActionResult> GetStudentResults([FromBody] MyPostModel postModel) 
+0

這不是在.NET 4.5的一個問題,是嗎?我可以發誓我記得在POST中發送多個參數 –

+3

@AlexKibler:只有通過表單發送參數或獲取查詢。你的身體只能有一個模型,所以任何非基本類型(int,string等)都會被序列化爲第一個模型。在ASP.NET Core(4.5或.NET Core的獨立)中,您只能擁有一個FromBody(在WebApi 2.x中是隱含的),因爲WebAPI和MVC現在被合併到一個框架中,之前它們是不同的框架 – Tseng