Can you enable [Authorize] for controller but disable it for a single action?

前端 未结 4 1083
长发绾君心
长发绾君心 2021-01-31 20:04

I would like to use [Authorize] for every action in my admin controller except the Login action.

[Authorize (Roles = \"Administrator\"         


        
4条回答
  •  旧时难觅i
    2021-01-31 20:49

    You could override the OnAuthorization method of the controller

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if ((string)(filterContext.RouteData.Values["action"]) == "Login")
            {
                filterContext.Cancel = true;
                filterContext.Result = Login();
            }
        }
    

    This works but it is a hack.

    Full class code used for testing:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
    
    namespace MvcApplication2.Controllers
    {
    [HandleError]
    [Authorize]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Title"] = "Home Page";
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
    
            return View();
        }
    
    
        public ActionResult About()
        {
            ViewData["Title"] = "About Page";
    
            return View();
        }
    
    
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if ((string)(filterContext.RouteData.Values["action"]) == "Index")
            {
                filterContext.Cancel = true;
                filterContext.Result = Index();
            }
        }
    }
    }
    

提交回复
热议问题