ASP.NET MVC Forms authentication and unauthenticated controller actions

前端 未结 3 1636
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 11:16

    I don't think there is an "Unauthorize" attribute that can be applied to actions and if you don't want to place "[Authorize]" on all but two actions in a controller try the following:

    Here are two methods I can think of:

    1- Location attribute in Web.config (Not sure if this will work with MVC routing etc.)

    After your

     stuff 
    

    in web.config file, add the following:

      
         
               
                  
              
          
      
    

    Where Account/ActionOne is the name of the action method you want to give anonymous access to. For the second Action, copy the above code and paste it right after it and change the name of the Action.

    I'm not sure if this will work because of MVC routing etc, but give it a try.

    2- Base Controller

    If the previous solution didn't work, your best bet would be to create a base controller that is decorated with the Authorize attribute:

    [Authorize]
    public class AuthorizeControllerBase : Controller {}
    

    Then have all your controllers inherit from it:

    public class AccountController : AuthorizeControllerBase
    {
          // your actions etc.
    }
    

    This will make any controller that inherits from AuthorizeControllerBase require authorization/logging in to invoke any methods.

    Then you would need to remove from your web.config

提交回复
热议问题