我在ASP.NET Core 2.0 Web API中有以下模型
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 = "me@me.com", 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", "me@me.com"),
new KeyValuePair<string, string>("password", "somePassword"),
}
var response = await client.PostAsync("/api/auth/login", content);
我也尝试使用HttpClient扩展,这也导致在发布时模型中没有显示任何值。
var credentials = new LoginModel() { Username = "me@me.com", Password = "somePassword" };
var response = await client.PostAsJsonAsync<LoginModel>("/api/auth/login", credentials);
我错过了什么?任何帮助将不胜感激。
答案 0 :(得分:1)