asp.net - 通过外键添加与用户 ID 相关联的位置
问题描述
我在这里学习 .NET 并构建了一个小型 API,允许我注册用户、检索用户列表或单个用户,以及编辑它们。Microsoft 标识用于此过程的大部分。
我现在正在尝试向此 API 添加新部分以处理物理位置。每个位置都将与特定用户绑定,因此每个用户可能有一个或多个位置。不过,我在构建它的这一部分时遇到了麻烦。我似乎无法弄清楚如何将用户的 ID 作为外键绑定到该位置。我已经和这个斗争了很长一段时间了。
我为位置调用和 DTO 构建了控制器,但它似乎并不想真正正常工作。
任何人都愿意说话并让我知道需要做什么以及如何做到这一点?我有点迷茫,真的很想了解它是如何工作的。带有完整工作项目的 github 存储库在这里:
解决方案
这里的问题是它的配置方式。
以下调整解决了该问题:
创建位置()方法:
[HttpPost]
public async Task<IActionResult> CreateLocation(int clientId, LocationCreateDto locationCreateDto)
{
// Grab the current users roles to verify they have access to this API call
var userRole = User.FindFirst(ClaimTypes.Role).ToString();
if (userRole != "http://schemas.microsoft.com/ws/2008/06/identity/claims/role: GlobalAdmin")
return Unauthorized();
// Create the new location
var newLocation = _mapper.Map<Locations>(locationCreateDto);
_repo.Add(newLocation);
if (await _repo.SaveAll())
{
var locationToReturn = _mapper.Map<LocationCreateDto>(newLocation);
return CreatedAtRoute(nameof(GetLocation), new { id = locationToReturn.Id, userid=clientId }, locationToReturn);
}
throw new Exception("Unable to create new location. Failed to save.");
}
HttpGet 方法:
[HttpGet("{id}", Name = nameof(GetLocation))]
public async Task<IActionResult> GetLocation(int id)
{
var location = await _repo.GetLocation(id);
var locationToReturn = _mapper.Map<LocationCreateDto>(location);
return Ok(locationToReturn);
}
推荐阅读
- visual-studio - Visual Studio 2019:开始页面而不是开始窗口
- google-sheets - 从模板导入公式
- spring - Spring mongodb ArrayOperators 按 $in 子句过滤
- ssl-certificate - 邮递员 Mac 中的 SSL 证书验证失败
- bash - 通过仅存在于远程的 ssh 运行 bash 命令
- react-native - 如何通过手机锁定 React Native 应用程序屏幕?
- c++ - 模板元:函数参数类型特征检测
- python - ElementTree XML-Parser,附加超链接写入标签
- r - ggplot2 geom_polygon 没有绘制任何东西
- java - 图像元数据未从 jpeg 复制到 tif 文件,使用 Java ImageIO 和十二猴子