c# - 如何防止访问者篡改POST Action 中的id字段?

标签 c# asp.net asp.net-mvc

首先考虑由 ASP.NET Core MVC 脚手架生成的以下代码片段。

// GET: Students/Delete/5
public async Task<IActionResult> Delete(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var student = await _context.Students
        .SingleOrDefaultAsync(m => m.ID == id);

    if (student == null)
    {
        return NotFound();
    }

    return View(student);
}

// POST: Students/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    var student = await _context.Students.SingleOrDefaultAsync(m => m.ID == id);
    _context.Students.Remove(student);
    await _context.SaveChangesAsync();
    return RedirectToAction("Index");
}

HttpGetHttpPost 的 Action 方法有一些区别如下:

  • id 在 Get 中可为空,但在 Post 中不可为空。
  • 如下初步检查仅在Get中。

代码:

    if (id == null)
    {
        return NotFound();
    }

    var student = await _context.Students
                .SingleOrDefaultAsync(m => m.ID == id);

    if (student == null)
    {
       return NotFound();
    }

问题:

例如,访问者在 GET 中请求删除 id=5,但后来他在 POST 中篡改了 id,将其设置为一个数字,例如 id=6 或将其设置为无效值,例如 id=xodsfsdofsdfosdfsd。由于HttpPost中没有进行初步检查,如何防止这种情况?

最佳答案

您可能希望在 POST 操作中添加检查以验证用户,因为 you cannot prevent tampering with the value .

删除学生的用户可能有也可能没有删除学生的权限。这取决于您的应用程序来决定。这不是脚手架工具可以为您决定的事情。

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    var authorized = ValidateStudentDeletion(User, studentId: id);

    if (authorized)
    {
        // delete student
        ...
        return RedirectToAction("Index");
    }
}

关于c# - 如何防止访问者篡改POST Action 中的id字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564427/

相关文章:

c# - 使用 .NET Rx 观察随 Action 事件改变的属性

javascript - ScriptManager 在 Mono 下不加载 javascript 方法

asp.net-mvc - asp.net mvc3 基于模型检查单选按钮

asp.net-mvc - 我的表单应该在我的编辑器模板内部还是外部?

javascript - 页面未通过调用 RedirectToAction 刷新

c# - 在数据库中保存用户设置

c# - Entity Framework 生成的 SQL 查询

C#:单例模式和静态模式的区别

asp.net - 匹配最多五个单词的正则表达式

javascript - 执行了 ajax 请求。如何格式化返回的数据?