ASP.NET MVC Forms authentication and unauthenticated controller actions

前端 未结 3 1570
Happy的楠姐
Happy的楠姐 2021-02-04 10:36

I have a ASP.NET MVC site that is locked down using Forms Authentication. The web.config has


    

        
3条回答
  •  不知归路
    2021-02-04 10:59

    Yes you can. In your AccountController there's an [Authorize]-attribute either on class-level (to make the whole controller restricted) or on specific methods.

    To make specific actions restricted you simply use the Authorize-attribute on the methods that handle these actions, and leave the controller-class unrestricted.

    Here are a few examples... hope it helps

    To require users to login, use:

    [Authorize]
    public class SomeController : Controller
    
    // Or
    [Authorize]
    public ActionResult SomeAction()
    

    To restrict access for specific roles, use:

    [Authorize(Roles = "Admin, User")]
    public class SomeController : Controller
    
    // Or
    [Authorize(Roles = "Admin, User")]
    public ActionResult SomeAction()
    

    And to restrict access for specific users, use:

    [Authorize(Users = "Charles, Linus")]
    public class SomeController : Controller
    
    // Or
    [Authorize(Users = "Charles, Linus")]
    public ActionResult SomeAction()
    

    As you can see, you can either use the attribute at class-level or at method-level. Your choice!

提交回复
热议问题