通过邮递员进行测试时,我的注册API不起作用:“状态代码:400;错误的请求”
问题描述:
当测试,我已经尝试输入从我RegisterViewModel
匹配,不管我已经使用邮递员后试了一下不同的输入用户这是行不通的,不确定的,如果它的东西与方法或我邮递员输入做。通过邮递员进行测试时,我的注册API不起作用:“状态代码:400;错误的请求”
的RegisterViewModel
看起来是这样的:
public class RegisterViewModel
{
[Required]
public string Username { get; set; }
[Required, DataType(DataType.Password)]
public string Password { get; set; }
[Required, DataType(DataType.Password)]
public string ReEnterPassword { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
继承人我尝试输入邮递员:
{
"username" : "user01",
"password" : "test123",
"reEnterPassword" : "test123",
"email" : "[email protected]",
"firstName" : "Joe",
"lastName" : "Bloggs"
}
所使用的方法:
[HttpPost("api/auth/register")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> NotWrkingRegister([FromBody] RegisterViewModel user)
{
if (user.Password != user.ReEnterPassword)
{
ModelState.AddModelError(string.Empty, "Password don't match");
return BadRequest();
}
try
{
var newUser = Mapper.Map<RegisterViewModel, AppUser>(user);
newUser.UserName = user.Username;
newUser.APIKey = Guid.NewGuid();
//newUser.Email = user.Email;
var userCreationResult = await userManager.CreateAsync(newUser, user.Password);
if (!userCreationResult.Succeeded)
{
foreach (var error in userCreationResult.Errors)
ModelState.AddModelError(string.Empty, error.Description);
return View(user);
}
else
{
string confirmationToken = userManager.
GenerateEmailConfirmationTokenAsync(newUser).Result;
string confirmationLink = Url.Action("ConfirmEmail",
"Account", new
{
userid = newUser.Id,
token = confirmationToken
},
protocol: HttpContext.Request.Scheme);
var callbackUrl = Url.Action("confirmEmail", "api/auth",
new { userId = newUser.Id.ToString(), code = confirmationToken },
protocol: HttpContext.Request.Scheme);
callbackUrl = $"http://localhost:49181/api/auth/confirmemail?userId=" + newUser.Id.ToString() + $"&token={confirmationToken}";
SendEmail(callbackUrl, newUser);
}
UserViewModel _userVM =
Mapper.Map<AppUser, UserViewModel>(newUser);
return new OkObjectResult(_userVM);
}
catch (Exception ex)
{
_logger.LogError($"Exception thrown while creating JWT: {ex}");
}
return BadRequest();
}
答
工作现在,有重复的值已经注册无线瘦数据库。在注释掉[ValidateAntiForgeryToken]
并通过指向每个单独组件的代码中断之后,找到问题并纠正并获得了所需的输出。
你是如何传递的反伪造令牌? – mjwills
services.AddAntiforgery(options => options.HeaderName =“X-XSRF-TOKEN”); 不知道,我试图在尝试获得不同的输出,当方法被调用它似乎并没有连打try catch块注释掉它。 – Bmanzr
您的PostMan请求未通过防伪标记。而'[ValidateAntiForgeryToken]'意味着你的代码需要它。因此,400 – mjwills