1

这是我现在做的事情,声明Roles允许访问我的控制器操作方法的字符串:

[Role(Roles="Regular User, Accounting, Administrator")]
public ActionResult ChangeAvatar()
{
    if (User.Identity.IsAuthenticated)
    {
        var user = _userRepository.FindUserByEmail(User.Identity.Name);
        var model = new ChangeAvatarModel();
        model.CurrentAvatarUrl = user.AvatarUrl;

        return View(model);
    }

    return RedirectToAction("Login", "Account");
}

我不想将其写成Roles字符串,因为我可能会输入错误并导致意外错误。我宁愿把它们写一次就完成了。

你建议我在这个用例中使用什么?一个dictionary<enum, string>

[Role(Roles=DefinedRoles.Accounting)] // Would return string: "Regular User, Account"
public ActionResult ChangeAvatar()
{
    if (User.Identity.IsAuthenticated)
    {
        var user = _userRepository.FindUserByEmail(User.Identity.Name);
        var model = new ChangeAvatarModel();
        model.CurrentAvatarUrl = user.AvatarUrl;

        return View(model);
    }

    return RedirectToAction("Login", "Account");
}
4

2 回答 2

2

您可以使用静态常量类:

public static class DefinedRoles
{
    public const string Accounting = "Regular User, Accounting, Administrator";
}
于 2012-09-20T15:50:51.267 回答
0

目前正在试验这种方法,到目前为止一切顺利..

public class StringEnum
{
    private static IDictionary<string, StringEnum> _items = new Dictionary<string, StringEnum>();

    public static readonly StringEnum Type1 = new StringEnum("TYPE1");
    public static readonly StringEnum Type2 = new StringEnum("TYPE2");

    private string _value;

    private StringEnum(string value)
    {
        _value = value;
        _items.Add(_value, this);
    }

    public static implicit operator StringEnum(string value)
    {
        return _items[value];
    }

    public static implicit operator string(StringEnum typeSafeValue)
    {
        return typeSafeValue._value;
    }

    public override bool Equals(object obj)
    {
        return obj.ToString() == _value;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public override string ToString()
    {
        return _value;
    }
}

可以像这样使用:

StringEnum type = StringEnum.Type1
于 2012-09-20T15:58:08.923 回答