ASP.NET CORE MVC我如何通过在html页面上基于UserId取消href链接来限制UserId可以编辑的内



此外,在创建新产品时,当前登录用户的UseId将动态添加到数据库中。

然而,如果当前登录用户的UserId与该项目的UserId不匹配,我正试图找到一种方法,使<a asp-action="Edit" asp-route-id="@item.Id">Edit</a>链接到dissapear(请参阅下面的模板(。

我试着关注这篇文章,但我不认为这会破坏任何链接。ASP.NET MVC属性,只允许用户编辑他/她自己的内容

型号

public class Product
{
public int Id { get; set; }
public string UserId { get; set; }
public V8User User { get; set; }
public string Name { get; set; }
public Double Price { get; set; }
public string Photo { get; set; }
}```

Snippet of the controller
// GET: Products/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = await _context.Product.FindAsync(id);
if (product == null)
{
return NotFound();
}
ViewData["UserId"] = new SelectList(_context.Set<V8User>(), "Id", "Id", product.UserId);
return View(product);

}

// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for 
// more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,UserId,Name,Price,Photo")] Product product)
{
if (id != product.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(product);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
ViewData["UserId"] = new SelectList(_context.Set<V8User>(), "Id", "Id", product.UserId);
return View(product);
}```

模板(Index.cshtml(

<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.User)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.Photo)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Photo)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>

首先,您应该获得当前登录用户的userId。然后在页面中决定是否隐藏编辑链接

@if(currentUserId == @item.Id)
{
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
}

逐字逐句的问题的答案是你不能。对用户隐藏链接不会阻止他们简单地将产品ID插入到他们可以看到的URL中,并访问他们不应该访问的项目。

您应该在Edit方法中添加UserId验证。

关于您的编辑(POST(方法,为什么要信任正在提交的UserId并允许它替换产品项的UserId?也许可以使用它来根据实际Product.UserId的查找执行验证,并确保有人没有试图提交错误的数据。

最新更新