首页 > 解决方案 > 通过外键添加与用户 ID 相关联的位置

问题描述

我在这里学习 .NET 并构建了一个小型 API,允许我注册用户、检索用户列表或单个用户,以及编辑它们。Microsoft 标识用于此过程的大部分。

我现在正在尝试向此 API 添加新部分以处理物理位置。每个位置都将与特定用户绑定,因此每个用户可能有一个或多个位置。不过,我在构建它的这一部分时遇到了麻烦。我似乎无法弄清楚如何将用户的 ID 作为外键绑定到该位置。我已经和这个斗争了很长一段时间了。

我为位置调用和 DTO 构建了控制器,但它似乎并不想真正正常工作。

任何人都愿意说话并让我知道需要做什么以及如何做到这一点?我有点迷茫,真的很想了解它是如何工作的。带有完整工作项目的 github 存储库在这里:

https://github.com/sapper6fd/API

标签: asp.net.netasp.net-core.net-core

解决方案


这里的问题是它的配置方式。

以下调整解决了该问题:

创建位置()方法:

[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);
        }

推荐阅读