2017-10-10 43 views
1

我有一个ASP.NET核2.0网页API的StringContent导致空但FormUrlEncodedContent正常工作

public class LoginModel 
{ 
    public string Username { get; set; } 
    public string Password { get; set; } 
} 

包含以下动作如下模型

[HttpPost] 
public async Task<IActionResult> Login(LoginModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, false, false); 
     if (result.Succeeded) 
     { 
      ApplicationUser user = await UserManager.FindByNameAsync(model.Username); 
      return new ObjectResult(await GenerateToken(user)); 
     } 
    } 
    return BadRequest(model); 
} 

使用的StringContent与JsonConvert在测试客户端中,当发布到控制器上的操作时,这会导致在模型中显示NULL值。

var credentials = new LoginModel() { Username = "[email protected]", Password = "somePassword" }; 
var content = new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json");   
var response = await client.PostAsync("/api/auth/login", content); 

当使用FormUrlEncodedContent时,模型在控制器上的操作中正确填充。

var content = new FormUrlEncodedContent(new[] 
{ 
    new KeyValuePair<string, string>("username", "[email protected]"), 
    new KeyValuePair<string, string>("password", "somePassword"), 
} 
var response = await client.PostAsync("/api/auth/login", content); 

我也试过使用HttpClient扩展,这也导致在发布时模型中没有显示值。

var credentials = new LoginModel() { Username = "[email protected]", Password = "somePassword" }; 
var response = await client.PostAsJsonAsync<LoginModel>("/api/auth/login", credentials); 

我错过了什么?任何帮助将不胜感激。

+3

的可能的复制[为什么在POST主体预期的数据,当我需要FromBody属性(HTTPS: //sackoveroverflow.com/questions/34529346/why-do-i-need-frombody-attribute-when-expecting-data-in-post-body) – Set

+0

不重复。答案可能是一样的,但问题不是。 –

回答

1

更新操作使用[FromBody]属性

[HttpPost] 
public async Task<IActionResult> Login([FromBody]LoginModel model) { 
    //...code removed for brevity 
} 

参考Asp.Net Core: Model Binding寻找在请求主体内容

相关问题