【问题标题】:ASP.NET MVC - Allow Users to only modify their own dataASP.NET MVC - 允许用户只修改自己的数据
【发布时间】:2017-06-22 05:35:35
【问题描述】:

我有一个与 AspNetUser 一对(一或零)关系的 UserProfile 模型。

用户资料:

public class UserProfile
{
    public int Id { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    [Required]
    [Display(Name = "Full Name")]
    public string FullName { get; set; }
}

如何验证正在修改的 UserProfile 是用户自己的数据? 我在我的 POST 和 GET 方法上放置了一个 [Authorize] 属性以进行编辑,但我仍然需要验证用户是否正在编辑他们自己的数据。

这可以使用另一个属性来完成,这样我就不必在我的方法中重复代码,如果可以,我该如何编码?

【问题讨论】:

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


    【解决方案1】:

    他们通常使用Autorize作为一般原则的属性。

    为了确保操作根据输入是合法的,最简单的方法是在方法控制器(ActionResult函数)中检查当前用户是否等于执行编辑的用户:

    [HttpPost]
    public ActionResult Edit(UserProfile model)
    {
        if(User.Identity.GetUserId() != model.ApplicationUser.Id)
            return new HttpUnauthorizedResult();
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多