【发布时间】:2016-07-18 13:04:20
【问题描述】:
我有一个属性来检查控制器操作中的身份验证。我的属性是这样的:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthenticationRequiredAttribute : ActionFilterAttribute, IAuthenticationFilter
{
private readonly bool checkAuthentication;
public AuthenticationRequiredAttribute(bool checkAuthentication)
{
this.checkAuthentication = checkAuthentication;
}
public void OnAuthentication(AuthenticationContext filterContext)
{
if (checkAuthentication && !UserIdentity.IsAuthenticated)
filterContext.Result = new HttpUnauthorizedResult();
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary{
{"controller", "Account"},
{"action", "Login"}
});
}
}
}
如果checkAuthentication = false 不检查认证。
除一项操作外,控制器中的所有操作都应检查身份验证。我在控制器上应用[AuthenticationRequired(true)],在特定操作上应用[AuthenticationRequired(false)]。但它不起作用,总是检查身份验证。
当将[AuthenticationRequired(true)] 应用于其他操作并将其从控制器中删除时,它可以正常工作。
在这种情况下如何强制使用方法属性?
【问题讨论】:
-
你能给我们检查属性的代码吗?
-
@LuisFilipe 我编辑我的问题并添加属性代码。
-
你想要什么?默认的 Authorize Attribute 不支持这样的事情并且有一个不同的属性:AllowAnonymous..see code here github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/… and see SkipAuthorization function 也许你也可以在你的场景中应用这种解决方案
标签: c# asp.net-mvc custom-attributes actionfilterattribute