ASP.NET MVC Attribute to only let user edit his/her own content

前端 未结 4 545
深忆病人
深忆病人 2020-12-04 20:29

I have a controller method called Edit in which the user can edit data they had created like so ...

public ActionResult Edit(int id)
{
    Submi         


        
4条回答
  •  独厮守ぢ
    2020-12-04 20:54

    I would suggest you pull the logic out of the action/controller and build a domain class to handle that logic.

    Action methods should really only deal with getting data from and sending data to the view. You could create something generic enough to handle your needs but will also follow the single responsibility principal.

    public class AuthorizedToEdit 
    {
         protected override bool AuthorizeCore(string user, int itemId)
         {
             var userName = httpContext.User.Identity.Name;
    
             var authUsers = SubmissionRepository.GetAuthoriedUsers(itemId);
    
             return authUsers.Contains(user);
         }
    }
    

    This would also allow you to have the flexibility later on to allow something like admin users

提交回复
热议问题