标识-ASP.NET核心MVC中的用户权限



我正在创建一个web应用程序,通过Identity登录的用户可以在其中创建新的销售对象(产品(。然而,我想知道如何使用Identity来创建它,以便用户只能看到自己创建的对象。我一直在考虑UserManager,但我对它还很陌生,所以我真的不确定从哪里开始。

如果有人能给我展示一个非常简单的方法来解决这个问题,我将不胜感激。我读了很多微软的文档,但我觉得自己并没有变得更聪明。

这是我的CCD_ 2;产品":

using auktioner_MarcusR91.Data;
using auktioner_MarcusR91.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace auktioner_MarcusR91.Controllers
{
public class InventoryController : Controller
{
private readonly AppDbContext _db;
public InventoryController(AppDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Inventory> objInventoryList = _db.Inventories;
return View(objInventoryList);
}
//GET
[Authorize]
public IActionResult Create()
{
return View();
}
//Post
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Inventory inventory)
{
_db.Inventories.Add(inventory);
_db.SaveChanges();
return RedirectToAction("index");
}
//GET
[Authorize]
public IActionResult Edit(int? id)
{
if (id == 0 || id == 5) 
{
return NotFound();
}
var inventoryFromDb = _db.Inventories.Find(id);
if (inventoryFromDb == null)
{
return NotFound();
}
return View(inventoryFromDb);
}
//Post
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(Inventory inventory)
{
if (ModelState.IsValid)
{
_db.Inventories.Update(inventory);
_db.SaveChanges();
return RedirectToAction("index");
}
return View(inventory);
}
}
}

如果有帮助的话,下面是我的创建视图:

@model Inventory
<form method = "post">
<div class = "border p-3 mt-4">
<div class = "row pb-2">
<h2 class = "text-primary">Add to Inventory</h2>
<hr />
</div>
<div class = "mb-3">
<label asp-for ="inventoryName"></label>
<input asp-for = "inventoryName" />
<label asp-for ="finalPrize"></label>
<input asp-for = "finalPrize" />
<label asp-for ="inventoryDesc"></label>
<input asp-for = "inventoryDesc" />
<p>1 för "Transport</p>
<p>2 för "Smycken"</p>
<p>3 för "Hushåll"</p>
<p>4 för "Dekoration"</p>
<select asp-for = "categoryId">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
<button type = "submit" class = "btn btn-primary" width = "100px">Submit</button>
<a asp-controller = "Inventory" asp-action = "index" class = "btn btn-secondary" style = "width: 100px">Back to products</a> 
</div>
</form>

U应该使用userManager作为userId。

private readonly AppDbContext _db;
private readonly UserManager<ApplicationUser> _userManager;
public InventoryController(AppDbContext db, UserManager<ApplicationUser> userManager)
{
_db = db;
_userManager = userManager;
}

然后按userId更改查询筛选器。

var userId = _userManager.GetUserId(HttpContext.User);
IEnumerable<Inventory> objInventoryList = _db.Inventories.Where(d => d.userId == userId);

最新更新