Asp.net mvc 4 MVC覆盖AllowAnonymous属性
有没有一种方法可以覆盖Asp.net mvc 4 MVC覆盖AllowAnonymous属性,asp.net-mvc-4,authentication,custom-attributes,filterattribute,Asp.net Mvc 4,Authentication,Custom Attributes,Filterattribute,有没有一种方法可以覆盖AllowAnonymous属性?我已实现自定义授权,从数据库加载用户菜单和按钮,如下所示: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new MyCustomAuthorization()); // Custom Authorization for Rights & Priveleges } 以上方法很好 现在我想允许访问一
AllowAnonymous
属性?我已实现自定义授权,从数据库加载用户菜单和按钮,如下所示:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyCustomAuthorization()); // Custom Authorization for Rights & Priveleges
}
以上方法很好
现在我想允许访问一些操作,如果用户经过身份验证,在这种情况下不需要检查授权。例如:
[Authorize]
public class MenusAndButtonsController : BaseController
{
[Authenticated] // my custom attribute that will check if user is logged in or not
public JsonResult GetGeneralMenuAndButtons()
{
using (MealPlannerAuthorizationEntities repository = new MealPlannerAuthorizationEntities())
{
var MenusAndButtons = repository.MP_AUTH_Menus.Where(x => x.IsButton == false && x.IsListButton == false).Select(c => new { DisplayText = c.MenuName, Value = c.MenuId }).OrderBy(x => x.DisplayText).ToList();
return Json(new { Result = "OK", Options = MenusAndButtons }, JsonRequestBehavior.AllowGet);
}
}
}
我正在尝试创建自己的自定义属性[Authenticated]
,以检查用户是否登录,而不是AllowAnonymous
。如果用户登录,它将返回true,并且GetGeneralMenuAndButtons
将继续其操作
实际上,AllowAnonymous
类是简单的空密封属性类
因此,当我们用AllowAnonymous
属性修饰动作方法时,AuthorizeAttribute
的onAuthorization
方法忽略了授权和身份验证检查。因此,在我的例子中,我还必须创建一个属性(一个从属性类继承的空白密封类),并稍微修改OnAuthorization
方法
以下是完整的实施:
public sealed class AuthenticateAttribute : Attribute
{
public AuthenticateAttribute() { }
}
然后重写authorization属性的onAuthorization
方法(当然我假设您已经实现了自定义授权过滤器)
最后,用我们新的Authenticate属性装饰您的操作方法:
[Authenticate]
public JsonResult GetParentMenus()
{
using (MealPlannerAuthorizationEntities repository = new MealPlannerAuthorizationEntities())
{
var parentMenus = repository.MP_AUTH_Menus.Where(x => x.IsButton == false && x.IsListButton == false).Select(c => new { DisplayText = c.MenuName, Value = c.MenuId }).OrderBy(x => x.DisplayText).ToList();
return Json(new { Result = "OK", Options = parentMenus }, JsonRequestBehavior.AllowGet);
}
}
[Authenticate]
public JsonResult GetParentMenus()
{
using (MealPlannerAuthorizationEntities repository = new MealPlannerAuthorizationEntities())
{
var parentMenus = repository.MP_AUTH_Menus.Where(x => x.IsButton == false && x.IsListButton == false).Select(c => new { DisplayText = c.MenuName, Value = c.MenuId }).OrderBy(x => x.DisplayText).ToList();
return Json(new { Result = "OK", Options = parentMenus }, JsonRequestBehavior.AllowGet);
}
}