【问题标题】:How to create a custom attributes that derive from AuthorizeAttribute?如何创建派生自 AuthorizeAttribute 的自定义属性?
【发布时间】:2013-04-09 14:49:20
【问题描述】:

用户创建帐户后,他/她需要创建一个个人资料,他/她在其中提交一些将用于信件的信息。我有 2 个这样的控制器需要来自用户个人资料的信息。

我正在尝试创建一个属性,该属性将在让用户访问任何操作方法之前检查用户是否已经创建了配置文件。如果没有,用户应该被重定向到个人资料页面

public class NotAuthorizedWithoutProfileAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var userName = httpContext.Profile.UserName;
        var repository = new OWRepository();
        var userInfo = repository.GetUserInfo(userName);

        if (userInfo == null)
            return false;
        else
            return true;
    }
}

我遇到的问题是关于用户名,即以下行

var userName = httpContext.Profile.UserName;

为什么它给null?然而,这就是我获取登录用户名的方式。

【问题讨论】:

    标签: asp.net-mvc-4 custom-attributes authorize


    【解决方案1】:

    我不知道您的个人资料配置是什么,但使用HttpContextBase.User.Identity.Name 获取用户名是最安全的。

    还可以考虑将您的班级名称更改为更短但也有意义的名称,例如 RequireProfileAttribute

    【讨论】:

    • 谢谢,它正在工作。唯一的问题是它将用户重定向到登录页面。我想将用户重定向到个人资料页面,即 Controller = UserInfo 和 action = ManageProfile()。
    • 没关系。这篇文章回答了这个问题:stackoverflow.com/questions/13284729/…
    猜你喜欢
    • 2015-10-06
    • 2021-09-02
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多