روش‌های مقابله با مشکل امنیتی Mass Assignment در ASP.NET Core
200, OK
https://andrewlock.net/preventing-mass-assignment-or-over-posting-in-asp-net-core/ icon
  • Use BindAttribute on the action method 
  • Use [Editable] or [BindNever] on the model 
  • Use two different models 
  • Use a base class 
  • Use ModelMetadataTypeAttribute 
  • Explicit binding via TryUpdateModelAsync<> 

This was a very quick run down of some of the options available to you to prevent mass assignment. Which approach you take is up to you, though I would definitely suggest using one of the latter 2-model approaches. There are other options too, such as doing explicit binding via TryUpdateModelAsync<> but the options I've shown represent some of the most common approaches. Whatever you do, don't just blindly bind your view models if you have properties that should not be edited by a user, or you could be in for a nasty surprise.

And whatever you do, don't bind directly to your EntityFramework models. Pretty please. 

روش‌های مقابله با مشکل امنیتی Mass Assignment در ASP.NET Core
  • #
    ‫۵ سال و ۳ ماه قبل، دوشنبه ۱۳ خرداد ۱۳۹۸، ساعت ۰۶:۵۱
    راه حل دیگر: استفاده از روش Containment بجای Inheritance
    public class UserModel
    {
        [MaxLength(200)]
        [Display(Name = "Full name")]
        [Required]
        public string Name { get; set; }
    }
    
    public class UserModalViewModel
    {
        public UserModel Model { get; set; }
        public bool IsAdmin { get; set; }
        public IReadonlyList<lookupitem> Roles { get; set; }
    }
    ‌‌‌
    اکشن متد متناظر با درخواست GET
    [HttpGet]
    public async Task<IActionResult> Edit(int id)
    {
        var user = await _service.FindAsync(id); //return Maybe<UserModel>
        if (!user.HasValue)
        {
            return NotFound();
        }
    
        // prepare model
        var model = new UserModalViewModel
        {
            Model = user.Value,
            IsAdmin = true,
            Roles = await _lookupService.ReadRolesAsync()
        };
        return View(model);
    }

    ‌‌‌‌
    اکشن متد متناظر با درخواست POST
    [HttPost]
    public async Task<IActionResult> Edit([Bind(Prefix = "Model")] UserModel model)
    {
        //todo: check ModelState and save model
        await _service.EditAsync(model);
    }