1

我有一个 MVC4 应用程序,并且正在为编辑表单填充模型。

public class GuestEventModel{

    public String name {get;set;}
    public Int32 GuestID {get;set;}
    public String Address {get;set;}
    public Int32 EventID {get;set;}


}

在我使用的表单中@Html.HiddenFor(m=> m.EventID)@Html.HiddenFor(m=> m.GuestID)因此在回帖中,模型填充了这些详细信息。我发现自己不得不在整个系统中重复代码以检查当前登录的用户是否可以更新这些客户详细信息以及客户是否属于该事件,因为

  1. 是什么阻止我通过使用检查元素或类似元素更改源代码来编辑 CustomerID 字段?这会导致系统会根据错误的 ID 更新错误的客户信息的问题吗?
  2. 我怎样才能阻止这个?
4

2 回答 2

2

这是一个非常普遍的问题,有很多方法可以解决它。但您可以简单地限制Data Access Layer仅获取已与用户 ID 关联的数据。

一旦用户在您的系统中成功通过身份验证,您应该将userIdSession加密保存在 中Cookie,并且决不依赖客户端传递 userId。

那么,你GuestEventModel可能是:

public class GuestEventModel
{
    public Int32 UserId { get; set; } // could also be a reference to a 'User' object
    public String name {get;set;}
    public Int32 GuestID {get;set;}
    public String Address {get;set;}
    public Int32 EventID {get;set;}
}

然后,无论何时您访问您的数据层/存储库:

public ActionResult Show(Int32 id)
{
     // assuming you changed your DAL/Repository accordingly
     var guestEvent = dataSource.GetUserEventById(id, Session["userID"] as Int32);

     // or.., assuming your DAL/Repository exposes IQueryable
     var guestEvent = dataSource<GuestEventModel>
                          .Where(x => x.UserId == Session["userID"] as Int32)
                          .Single(x => x.Id == id);

     // ....
     return View(eventViewModel);
}
于 2013-07-14T08:32:44.257 回答
0

There is nothing stopping a user editing this client-side, as you pointed out.

You don't have to populate it from HTML though. Inside your post method, you can assign the EventID and the GuestID to the model from the server to prevent anyone changing it.

public ActionResult SaveEvent(GuestEventModel model) {
   model.EventID = this.Database.GetEventId();
   model.GuestID = this.Database.GetGuestId();
}
于 2013-07-14T08:01:54.160 回答