I have a project and user Model that inherits the default identity class.
These two share a many to many relationship.
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; }
}
I also have a project controller where I want to display ALL projects that contain the current user. (projects can have multiple users) I also want to be able to create projects.
[Authorize]
public IActionResult Index(string id)
{
IEnumerable<Project> objProjectList = _unitOfWork.Project.GetAll();
return View(objProjectList);
}
I started off by passing the user id through an anchor tag like so.
<a
asp-area="" asp-controller="Project" asp-action="Index"
asp-route-id="@UserManager.GetUserId(User)">Projects</a>
How do I use the id to get the projects that only contain the user corresponding to the id in my project controller?
How can I use the same id to create a project with the user attached on a post route in the same controller?
Should I avoid passing sensitive data like user id through anchor tags and get the user id some other way?
I'd appreciate any input, thanks.
CodePudding user response:
You can try something like this . But is good idea to use ViewModels ti protect your database. Also, all your logic should be in Service classes not in the controllers. The way You pass the Id is totally fine.
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();
}
}
Give the Service to the dependency container in the StartUp class
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IProjectService , ProjectService >();
}
Then you call the Service in the Controller
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 are more things to do, such as repositories, dtos eg, but this will be a good for the beginning