我有这个AuthController,我想使用CreatedAtRoute方法在UsersController中运行一个操作以返回插入的用户,但是它给出了此错误:
InvalidOperationException: No route matches the supplied values.
此处显示AuthController。用户注册,并在成功注册后调用UsersController的GetUser操作:
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;
private readonly ITokenService _tokenService;
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
private readonly IUserService _userService;
private readonly SignInManager<User> _signInManager;
private readonly ILogger _logger;
public AuthController(IConfiguration config,
ITokenService tokenService,
IMapper mapper,
UserManager<User> userManager,
SignInManager<User> signInManager,
IUserService userService,
ILogger<AuthController> logger)
{
_tokenService = tokenService;
_userManager = userManager;
_signInManager = signInManager;
_mapper = mapper;
_config = config;
_userService = userService;
_logger = logger;
}
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody]UserForRegisterDto userForRegisterDto)
{
_logger.LogInformation(LoggingEvents.InsertItem, "Registering user {UserName}", userForRegisterDto.UserName);
var userToCreate = _mapper.Map<User>(userForRegisterDto);
var result = await _userManager.CreateAsync(userToCreate,"1234567a" /*userForRegisterDto.Password*/);
var userToReturn = _mapper.Map<UserForLoginReturnDto>(userToCreate);
if (result.Succeeded)
{
_logger.LogInformation(LoggingEvents.InsertItem, "Registering user {UserName}", userForRegisterDto.UserName);
return CreatedAtRoute("GetUser",
new { controller = "Users", id = userToCreate.Id }, userToReturn);
}
_logger.LogError(LoggingEvents.InsertItem, "Registering user failed: {UserName}", userForRegisterDto.UserName);
return BadRequest(result.Errors);
}
}
UsersController如下:
[Route("api/users/{userId}/users")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
public UsersController(IUserService userService,
UserManager<User> userManager,
IMapper mapper)
{
_userService = userService;
_userManager = userManager;
_mapper = mapper;
}
[Authorize(Roles = "Admin, Manager, User")]
[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> GetUser(int id)
{
var isCurrentUser = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) == id;
var user = await _userService.GetUser(id, isCurrentUser);
var userToReturn = _mapper.Map<UserForLoginReturnDto>(user);
return Ok(userToReturn);
}
}
如何使用CreatedAtRoute方法寻址UsersController?
答案 0 :(得分:2)
这是路由问题。您缺少目标路线的值
return CreatedAtRoute("GetUser", new { id = userToCreate.Id, userId = {some value here} }, userToReturn);