asp.net mvc添加到“授权”属性
如何创建自定义属性以扩展MVC中现有的Authorize属性?从AuthorizeAttribute派生类。重写OnAuthorization方法。添加并设置CacheValidationHandlerasp.net mvc添加到“授权”属性,asp.net,asp.net-mvc,attributes,Asp.net,Asp.net Mvc,Attributes,如何创建自定义属性以扩展MVC中现有的Authorize属性?从AuthorizeAttribute派生类。重写OnAuthorization方法。添加并设置CacheValidationHandler public class CoolAuthorizeAttribute : AuthorizeAttribute { } public void CacheValidationHandler( HttpContext context,
public class CoolAuthorizeAttribute : AuthorizeAttribute
{
}
public void CacheValidationHandler( HttpContext context,
object data,
ref HttpValidationStatus validationStatus )
{
validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}
public override void OnAuthorization( AuthorizationContext filterContext )
{
if (filterContext == null)
{
throw new ArgumentNullException( "filterContext" );
}
if (AuthorizeCore( filterContext.HttpContext ))
{
... your custom code ...
SetCachePolicy( filterContext );
}
else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
else
{
... handle a different case than not authenticated
}
}
protected void SetCachePolicy( AuthorizationContext filterContext )
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidationHandler, null /* data */);
}
您不需要扩展此属性,web.config就足够了。请阅读。请注意defaultUrl。这是你需要的东西
<system.web>
<authentication mode="Forms">
<forms defaultUrl="YourUrlGoesHere"/>
</authentication>
</system.web>
我建议,如果您只想扩展当前的authorized属性并在其上添加您自己的授权,而不是覆盖授权,只需覆盖AuthorizeCore并向其添加MyCustomAuthorizationHolds条件即可
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (base.AuthorizeCore(httpContext) && MyCustomAuthorizationHolds)
return true;
return false;
}
}
请添加更多详细信息,你到底想扩展什么?现在我只想能够重定向到正确的页面,而不是默认的主页。你可以更新你的问题,这样每个人都可以知道你需要什么。但这不是动态的。url更改。嗯,为什么不在给出解决方案之前指定所有要求?不!这是完全错误的:哦。如果该博客条目的开头图中的断言是正确的,那么您可能应该减少损失并删除答案。我如何才能使角色起作用?它现在工作正常,但似乎角色不起作用。此外,即使用户经过身份验证,AuthorizeCore也会不断返回false,这意味着SetCachePolicy()永远不会执行。@Nick-此后,我在博客中谈到如何改进缓存处理方面: