【问题标题】:Implement custom "ValidateUser" in MembershipProvider在 MembershipProvider 中实现自定义“ValidateUser”
【发布时间】:2011-03-25 10:32:38
【问题描述】:

我正在实现一个自定义 MembershipProvider,我正在尝试使用 ValidateUser 方法来验证我在 SQL Server 中的 Profiles 表。此表有名为UserName 和Password 的列。

public override bool ValidateUser(string username, string password)
{
    ??? what to do here???
}

仅供参考,我使用的是 MVC3 和 EF 4.1 Code First。

谢谢

保罗

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-membership membership-provider code-first


    【解决方案1】:

    如果您使用的是 EF 4.1,您将拥有某种 DbContext 对象,其中包含用于您的 Profiles 表的 DbSet - 对吧?

    所以在这种情况下,使用这个:

    public override bool ValidateUser(string username, string password)
    {
        using(DbContext yourCtx = new DbContext())
        {
            // from your "Profiles" DbSet, retrieve that single entry which
            // matches the username/password being passed in
    
            var profile = (from p in yourCtx.Profiles
                          where p.UserName == username && p.Password == password
                          select p).SingleOrDefault();
    
            // if that query returns a "Profile" (is != null), then your
            // username/password combo is valid - otherwise, it's not valid
            return (profile != null);
        }
    }
    

    【讨论】:

    • excellent :) 但是 VS 不喜欢这条线: using(DbContext yourCtx = new DbContext()) ...says 'System.Data.Entity.DbContext.DbContext()' is inaccessible because它的保护级别谢谢保罗
    • @Paul Brown:你需要用你的具体数据库上下文替换DbContext(我不知道它叫什么——它应该是一个派生自DbContext的类)
    • @marc_s - 太好了,搞定了。现在最后一件事......“var profile”正在给出“无法将方法组分配给隐式类型的局部变量”任何想法?非常感谢您的帮助!
    • @Paul Brown:哦,对不起-我的错-.SingleOrDefault() 是一种方法,因此最后需要一对括号...
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多