在我的C#MVC4应用程序,我从一个自定义的授权内进行了几个不同的重定向行为属性取决于用户是否登录,在一定的作用,等等。自定义授权属性重定向当未经授权
我已将授权属性放在我的一个操作结果上方。如果用户没有登录,或没有通过身份验证或登录,但不是我检查的任何一个组的成员,我希望执行操作结果中的代码。如果用户已经登录并且是任一组的成员,我想要重定向到另一个操作(目前正在工作)。
使用我当前的代码,那些已登录和指定组内的内容将根据需要重新定向。所有其他类别中列出的,导致我的AuthorizationContext为null。知道当这是空的HandleUnauthorizedRequest被调用时,我试图覆盖它以允许访问原始动作结果,但无法弄清楚。
不管我怎么努力我收到的错误:Object Reference not set to an instance of an object
上与线:filterContext.Result = new RedirectToRouteResult(
我的授权属性代码如下:
public class AuthorizeEditAttribute : AuthorizeAttribute
{
public string hName { get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
// Check if user is authenticated and if this action requires authorization
if (filterContext.HttpContext.User.Identity.IsAuthenticated
&& filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
{
List<object> attributes = new List<object>(filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true));
attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true));
hName = filterContext.Controller.ValueProvider.GetValue("hSearch").AttemptedValue;
// Check all authorzation attributes
foreach (var attribute in attributes)
{
var authAttribute = attribute as AuthorizeAttribute;
if (authAttribute != null)
{
if ((filterContext.HttpContext.User.IsInRole("TCL-CAdmin")) || (filterContext.HttpContext.User.IsInRole("TCL-C Group")))
{
// User is not authorized to perform edits so redirect to Index_Perm ActionResult
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
//{ "area", "" },
{ "controller", "Home" },
{ "action", "Index_Perm" },
{ "hSearch", hName.ToString() }
});
break;
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
//{ "area", "" },
{ "controller", "Home" },
{ "action", "Index" },
{ "hSearch", hName.ToString() }
});
break;
}
}
}
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "Index" },
{ "hSearch", hName.ToString() }
});
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "Index" },
{ "hSearch", hName.ToString() }
});
}
}
}
而不是覆盖HandleUnauthorizedRequest,我自己也尝试修改OnAuthorization的开始部分看起来像这样:
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "controller", "Home" },
{ "action", "Index" },
{ "hSearch", hName.ToString() }
});
}
我仍然收到相同的警告对象引用。