在我的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() }
});
}
我仍然收到相同的警告對象引用。