C# 无法防止使用客户id过度过帐
我有一个简单的MVC应用程序 在编辑操作中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)
[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
将永远不会在客户端上,并且不能更改为将其发布到服务器上
注意事项:
customerId
,记住用户拥有HTML,他可以进行任何更改随机密钥
存储在会话
中,因此密钥的时间寿命有限,用户无法复制密钥供以后使用一种防止篡改隐藏字段以包括另一个包含
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——尽管我不明白你为什么要包含两次)