【发布时间】:2016-08-15 19:59:00
【问题描述】:
是否可以在剃刀视图中使用自定义过滤器?
例如,我有这个在控制器中工作:
[Privilege(Privileges ="AdminRead, AdminWrite"))]
public ActionResult Index()
{
return View();
}
但是是否有可能在 Razor cshtml 文件中执行以下操作:
if(@[Privilege(Privileges ="AdminRead, AdminWrite"))])
{
//html goes here
}
如果有所不同,则 PrivilegeAttribute 派生自 AuthorizeAttribute。
PrivilegeAttribute.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace IdentityDevelopment.Infrastructure
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class PrivilegeAttribute : AuthorizeAttribute
{
private static readonly string[] _emptyArray = new string[0];
private string _privileges;
private string[] _privilegesSplit = _emptyArray;
public string Privileges
{
get { return _privileges ?? String.Empty; }
set
{
_privileges = value;
_privilegesSplit = SplitString(value);
}
}
internal static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
{
return _emptyArray;
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
public PrivilegeAttribute(string privilegeList)
{
_privileges = privilegeList;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized) {
string[] rolesArray;
var roles = ((ClaimsIdentity)httpContext.User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);
rolesArray = roles.ToArray();
//Assume that a user can only be associated to 0 or 1 role. If 0 the rolesArray will be null.
if (rolesArray != null)
{
string roleUser = rolesArray[0];
SQLRolerecord CheckPrivInRole = new SQLRolerecord();
return CheckPrivInRole.Allow(roleUser, _privilegesSplit);
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
谢谢。
【问题讨论】:
-
这不可能吗?
@if (User.IsInRole("WhateverUserRole")) -
或
@if(User.IsAuthorized)应该这样做 -
@techspider 是的,我已经使用了它,这是可能的,但是自定义 AuthorizeAttributes 呢?例如,我有一个名为 PrivilegeAttribute 的函数,它接受一个名为“Privileges”的输入,那么我如何能够对此做类似的事情呢?如何创建一个名为 IsInPrivilege 的方法?
-
属性或过滤器不是视图而是控制器方法;您可以使用自定义 HTML 辅助方法来完成此操作
-
@jbutler483 我更新了我的问题,重点关注基于 AuthorizeAttribute 的自定义过滤器。
标签: html asp.net asp.net-mvc razor