【发布时间】:2021-08-24 02:47:41
【问题描述】:
我有一个学习项目。我想为用户实现基于资源的授权。我在控制器中开发了一个受保护的方法UserId(),我在 get 和 post 方法上调用它,类似于下面显示的代码。
我只是想问一下,这个解决方案是否可行,或者使用 Identity 框架有更好的方法来做到这一点,非常欢迎任何想法 :)
// protected UserId method
protected string UserId()
{
return User.FindFirstValue(ClaimTypes.NameIdentifier);
}
// GET view for categories, here I call the UserId method to check if items for that user exist.
public IActionResult Index()
{
List<Category> model = _categoryService.GetCategories().Where(x => UserId().Contains(x.UserId)).ToList();
return View(model);
}
// POST method for category
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Category category)
{
if (ModelState.IsValid)
{
category.UserId = UserId();
_categoryService.CreateCategory(category);
return RedirectToAction("Index");
}
return View(category);
}
// my Category model
public class Category
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
}
【问题讨论】:
标签: c# entity-framework-core asp.net-core-mvc asp.net-identity