是否可以在剃鬚刀視圖中使用自定義濾鏡?是否可以在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