mut*_*y91 7 c# asp.net-mvc asp.net-mvc-5
我正在使用自定义过滤器(定义如下):
if (user == null || !user.Active)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "Home"},
{"action", "NotAuthorized"}
});
}
base.OnActionExecuting(filterContext);
Run Code Online (Sandbox Code Playgroud)
这是在站点范围RegisterGlobalFilters()内运行的(在FilterConfig.cs中.但是,有一个页面我想允许访问 - NotAuthorized页面.在HomeController中,我创建了以下ActionResult方法:
[AllowAnonymous]
public ActionResult NotAuthorized()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
未经授权会将用户引导至此视图,但会导致重定向循环(可能是因为此过滤器仍在此页面上运行).
如何允许匿名用户访问此页面?
Ste*_*tty 12
您需要在自定义过滤器中检查属性.
尝试:
if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false)
&& !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false)
&& (user == null || !user.Active))
{
//....
}
Run Code Online (Sandbox Code Playgroud)
检查AllowAnonymousAttribute您的自定义过滤器中的 。这是一种可重复使用的方法。
添加以下扩展方法。
public static class MyExtensionMethods
{
public static bool HasAttribute(this ActionExecutingContext context, Type attribute)
{
var actionDesc = context.ActionDescriptor;
var controllerDesc = actionDesc.ControllerDescriptor;
bool allowAnon =
actionDesc.IsDefined(attribute, true) ||
controllerDesc.IsDefined(attribute, true);
return allowAnon;
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的过滤器中使用它。
public class MyActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// use the extension method in your filter
if (filterContext.HasAttribute(typeof(AllowAnonymousAttribute)))
{
// exit early...
return;
}
// ...or do whatever else you need to do
if (user == null || !user.Active)
{
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "NotAuthorized" }
});
}
base.OnActionExecuting(filterContext);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个实现解决方案的小提琴。
| 归档时间: |
|
| 查看次数: |
6626 次 |
| 最近记录: |