I Create my won Authorize Attribute. Thats work great in the controller. How can I use it in the view.
Example : I have a manage user link, If you haven't access to this page, I don't want to show the link.
Here is my Authorize Attribute.
public class UserAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Session["UserID"] == null)
{
return false;
}
IIssUserRepository repUser = new IssUserRepository(EntityFactory.GetEntity());
IssUser usr = repUser.GetUserByID(Convert.ToInt32(httpContext.Session["UserID"]));
return usr.CanManageUser;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "clubShortName", filterContext.RouteData.Values[ "clubShortName" ] },
{ "area",""},
{ "controller", "Account" },
{ "action", "Unauthorized" }
});
}
}
}
Here is how I use it in the controller:
[UserAuthorize开发者_如何学编程]
public class UserController : Controller
I need to use that in the view. But how
<li class="CssMenui">Product</li>
<%if (......... UserAuthorize .......) %>
<li class="CssMenui">User Management</li>
<li class="CssMenui">Other</li>
Stupid solution is to add flag to ViewData in your overriding for OnAuthorization
:
var view = filterContext.Result as ViewResult; if (view != null) view.ViewData["IsAuthorized"] = !(filterContext.Result is HttpUnauthorizedResult);
and after that your view can be rewritten:
<li class="CssMenui">Product</li> <%if (((bool?)ViewData["IsAuthorized"]) == true) %> <li class="CssMenui">User Management</li> <li class="CssMenui">Other</li>
Looks a little dirty for me, but it could help.
精彩评论