C# 无法防止使用客户id过度过帐

C# 无法防止使用客户id过度过帐,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个简单的MVC应用程序 在编辑操作中 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(string CustomerId, [Bind(Include = "CustomerId,CompanyId,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)

我有一个简单的MVC应用程序

在编辑操作中

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string CustomerId, [Bind(Include = "CustomerId,CompanyId,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
    var user = db.Users.Find(CustomerId);
    if (user != null)
        TryUpdateModel(user);
    else
        return HttpNotFound();
    if (ModelState.IsValid)
    {
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}
但是,当我执行F12并更改
CustomerId
的隐藏字段值时,不应该执行更改的
CustomerId

我想防止过度发布
CustomerId

1.如果使用F12更改了
CustomerId
,则抛出错误。 2.如果
CustomerId
正确无误,则只需更新所有值即可

我有个例外:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Attaching an entity of type 'MVCDemo.Models.Customer' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

我认为有很多方法可以做到这一点,我脑海中出现的最简单的方法就是这样

  • 生成
    randomKey
    (可以是Guid或其他内容)将
    customerId
    存储在
    Session[randomKey]=customerId
    中,这是在渲染包含表单的视图之前发生的

  • 在隐藏字段存储
    randomKey
    中,当您在服务器端发布帖子时,从
    Session
    获取
    customerId
    customerId=Session[randomKey]

  • 这样一来,
    customerId
    永远不会在客户端上,并且不能更改为将其发布到服务器上

    注意事项:

  • 用户可以使用F12更改
    customerId
    ,记住用户拥有HTML,他可以进行任何更改

  • 也许你可以用javascript捕捉到这个变化,但是如果他禁用javascript并改变值会发生什么呢

  • 由于
    随机密钥
    存储在
    会话
    中,因此密钥的时间寿命有限,用户无法复制密钥供以后使用


  • 一种防止篡改隐藏字段以包括另一个包含
    CustomerId
    值散列的隐藏字段的技术。然后在POST方法中,您可以比较这些值,并知道其是否被篡改


    讨论包括自定义html帮助程序在内的生成隐藏输入的技术。

    这与用户编辑数据有关吗?当您的
    客户
    模型似乎也有属性
    客户ID
    时,为什么要有参数
    字符串CustomerId
    ?您指定它包含在绑定中,那么您期望什么呢?看起来我们可能还需要try update model代码来实现该例外如果用户同时在两个不同的选项卡中编辑两个客户会发生什么情况?@StephenMuecke没有问题,因为您将
    CustomerId
    存储在
    随机键下(每次渲染编辑视图时生成)。这意味着每个
    CustomerId
    都有一个
    randomKey
    。这取决于您如何实现这一点,您可以为同一
    CustomerId
    拥有多个
    randomKey
    ,这样可以防止用户复制粘贴randomKey并在以后使用。因此,没有直接的方法来代替比较CustomerId?我认为必须这样做是一些防止被排除的功能items@ashu我认为不存在这样的功能,因为它更可能与应用程序的要求结合在一起。在我的解决方案中,您不必比较Id,而是将Id保留在服务器端并发送令牌(而不是Id)对于用户,当进行编辑时,id将基于该令牌进行检索。因此,没有直接的方法来代替比较CustomerId?我认为必须有一些功能来防止排除项。您已在
    [Bind(Include=…)]
    中指定了属性,因此它将被绑定(无论如何,你都需要包含它,否则你在发帖时永远不会知道ID——尽管我不明白你为什么要包含两次)