我有一個繼承默認身份類的專案和用戶模型。
這兩個共享多對多關系。
public class Project
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public ICollection<AppUser> users { get; set; }
}
public class AppUser : IdentityUser
{
public string DisplayName { get; set; }
public ICollection<Project> projects { get; set; }
}
我還有一個專案控制器,我想在其中顯示包含當前用戶的所有專案。(專案可以有多個用戶)我也希望能夠創建專案。
[Authorize]
public IActionResult Index(string id)
{
IEnumerable<Project> objProjectList = _unitOfWork.Project.GetAll();
return View(objProjectList);
}
我開始通過像這樣的錨標記傳遞用戶 ID。
<a class="nav-link text-dark"
asp-area="" asp-controller="Project" asp-action="Index"
asp-route-id="@UserManager.GetUserId(User)">Projects</a>
如何使用 id 獲取僅包含與我的專案控制器中的 id 對應的用戶的專案?
如何使用相同的 id 來創建一個專案,并將用戶附加到同一控制器中的 post 路由上?
我是否應該避免通過錨標簽傳遞敏感資料(如用戶 ID)并以其他方式獲取用戶 ID?
我很感激任何意見,謝謝。
uj5u.com熱心網友回復:
你可以試試這樣的。但是使用 ViewModels 來保護您的資料庫是個好主意。此外,您的所有邏輯都應該在服務類中,而不是在控制器中。你傳遞身份證的方式完全沒問題。
public interface IProjectService
{
IEnumerable<Project> GetAllProjectsByUserId(object userId);
}
public class ProjectService : IProjectService
{
public IEnumerable<Project> GetAllProjectsByUserId(string userId)
{
return _unitOfWork.Project.Where(x => x.users.Any(x =>
x.Id = userId)).ToList();
}
}
將 Service 賦予 StartUp 類中的依賴容器
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IProjectService , ProjectService >();
}
然后你在Controller中呼叫Service
private readonly IProjectService projectService;
public ControllerName(IProjectService projectService)
{
this.projectService = projectService;
}
[Authorize]
public IActionResult Index(string id)
{
var viewModel = projectService.GetAllProjectsByUserId(id);
return View(objProjectList);
}
Тhere 還有更多事情要做,例如存盤庫、dtos 等,但這對于開始來說是一個很好的選擇
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459582.html
下一篇:vue 模板指令練習demo1
