如何在 MVC 中忽略查询字符串中的模型绑定
我有表单提交并回发。控制器操作接受这些值作为参数。例如:EditProduct(int ProductID, string Productname)。
Productid 由隐藏字段中的表单提供。我怎样才能确保用户 不会调用此操作并将此产品 ID 和名称作为查询字符串传递,并且模型绑定将绑定值并将产品保存在数据库中?
I have form submission doing a post back. The controller action accepts the values as parameters. For ex: EditProduct(int productid, string productname).
productid is supplied from the form in a hidden field. How can I ensure that that a user
will not invoke this action and pass this productid and name as queystring and the model binding will bind the vales and product is saved in database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我发现最安全的方法是检查用户是否有权编辑产品。在操作中执行任何数据库更新之前检查此项,您无需担心用户修改隐藏值。
如果您想强制用户转到您的网页来执行帖子,可以使用 Html.AntiForgeryToekn()。但是,用户仍然可以访问该网站,查看防伪令牌并将其与请求一起传递。
I've found that the most secure approach would be to check that the user has permission to edit the product. Check this before you do any database updates in the action and you won't need to worry about users that modify the hidden values.
If you want to force users to go to your webpage to execute the post, you can use Html.AntiForgeryToekn(). However, a user can still visit the website, see the anti forgery token and pass it in with their request.
您可以使用服务器上的密钥(使用 HMACSHA512)对产品 ID 进行签名,然后在回发中验证签名。
您可能希望在签名时包含当前日期和/或用户或会话 ID,以防止重放攻击。
You can sign the product ID with a secret key on your server (using HMACSHA512), then verify the signature in the postback.
You might want to include the current date and/or the user or session ID when signing to prevent replay attacks.
您应该在
EditProducts
操作中实施适当的访问控制,以便尝试编辑不同的产品将生成错误。尝试阻止用户修改查询字符串不会有帮助。
You should implement proper access controls in the
EditProducts
action so that attempting to edit a different product will generate an error.Trying to prevent users from modifying the querystring won't help.
我建议您在模型中添加 rowversion (时间戳)列。这比签名或散列容易得多(如果您可以更改模型)。
I would suggest you add a rowversion (timestamp) column to your model. That is a lot easier (if you can make changes to the model) than signing or hashing.