是否可以在剃须刀视图中使用自定义滤镜?是否可以在Razor视图中使用基于AuthorizeAttribute的自定义过滤器?
例如,我有这样的工作在一个控制器:
[Privilege(Privileges ="AdminRead, AdminWrite"))]
public ActionResult Index()
{
return View();
}
但是,有没有可能做一些像剃刀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”))' – techspider
或'@if(User.IsAuthorized)'应该这样做 – jbutler483
@techspider是的,我已经使用过它,这是可能的,但自定义AuthorizeAttributes呢?例如,我有一个名为PrivilegeAttribute的接受名为“Privileges”的输入,那么我将如何能够做出类似的事情呢?我如何创建一个名为IsInPrivilege的方法? – ITWorker