ASP.NET MVC 2 - 成员资格提供程序 - ValidateUser() - 返回登录错误消息

时间:2010-03-03 16:12:40

标签: asp.net asp.net-mvc asp.net-mvc-2 asp.net-membership

如何从自定义成员资格提供程序中的ValidateUser方法返回字符串消息?我需要这个,因为我想执行几项检查(用户被批准,用户被阻止等),如果登录过程失败,则给用户一个很好的描述。

一种选择是抛出异常,但有人说这不是处理这种情况的正确方法。

目前我只能说因为bool返回类型而“登录失败”或“登录成功”。

是否可以创建自己的ValidateUser方法,或者ASP.NET成员资格机制是否使用其内部操作中的默认方法?

3 个答案:

答案 0 :(得分:2)

这是两种不同的操作。

要查看用户是否获得批准,已锁定等,请查看用户(使用GetUser())并查看IsApprovedIsLockedOut等属性。返回的用户。 ValidateUser()仅用于登录,但您可以同时执行这两项操作。

答案 1 :(得分:2)

可以在您的自定义提供商上实施您想要的任何方法,在您的情况下可能有意义这样做而且只是在使用之前将会员资格转换为您的类型。

但是打破界面以获得一些简单的带外信息可能会在未来再次出现。还有其他方法可以做到这一点并保留提供者api并保持未来的选择。

过去,我使用cookie将提供商之类的带外信息传递给消费者。

HttpContext.Current对于提供者和页面的相同,因此可以在使用者中读取提供者中设置的cookie。

请确保在致电提供商后删除 Cookie。创建一个临时cookie有助于最大限度地减少错误,但无论如何只需将其从集合中删除。

这是一个有效的例子。

<强> CookieChannelMembershipProvider

using System;
using System.Web;
using System.Web.Security;

namespace CookieChannel
{
    public class CookieChannelMembershipProvider : MembershipProvider
    {
        public override bool ValidateUser(string username, string password)
        {
            if(username=="asshat")
            {
                HttpContext.Current.Request.Cookies.Add(new HttpCookie("__cookiechannel", "user is an asshat. do not let him in."));
                return false;
            }
            return true;
        }

        #region Not implemented

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override string ApplicationName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }


        public override MembershipUser CreateUser(string username, string password, string email,
                                                  string passwordQuestion, string passwordAnswer, bool isApproved,
                                                  object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password,
                                                             string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }


        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize,
                                                                 out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
                                                                  out int totalRecords)
        {
            throw new NotImplementedException();
        } 
        #endregion
    }
}

<强>的Web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Windows" />
    <membership defaultProvider="cookieChannelProvider" userIsOnlineTimeWindow="15">
      <providers>
        <add
          name="cookieChannelProvider"
          type="CookieChannel.CookieChannelMembershipProvider, CookieChannel"
          connectionStringName="none"
          enablePasswordRetrieval="true"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="true"
          />
      </providers>
    </membership>
  </system.web>
</configuration>

<强> Default.aspx的

<%@ Page Language="C#" %>
<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        ValidateUser("user", "user");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        ValidateUser("asshat", "asshat");
    }

    private void ValidateUser(string username, string password)
    {
        bool validated = Membership.ValidateUser(username, password);
        string message = validated.ToString();

        if (Request.Cookies["__cookiechannel"] != null)
        {
            message += ":" + Request.Cookies["__cookiechannel"].Value;
            Request.Cookies.Remove("__cookiechannel");
        }
        Label1.Text = message;
    }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Validate Valued User" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
            Text="Validate Asshat User" />

    </div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

答案 2 :(得分:0)

你必须创建自己的机制;默认情况下不会发生此情况,也无法使用内置成员资格提供程序完成此操作。您可以包装该提供程序并添加此方法并自己执行...这是一个选项。但是,如果你使用登录控件,这不符合。