实现自定义 MembershipUser 和自定义 MembershipProvider

发布于 2024-10-30 09:31:41 字数 17159 浏览 4 评论 0原文

我尝试在自己的数据库中使用自定义 MembershipUser 实现自定义 MembershipPriver (具有特定的用户表模型):

这是完全不同的文件:

iTwitterMembershipProvider.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections.Specialized;
using iTwitter.Models;


 public class iTwitterMembershipProvider : MembershipProvider
{

    public override string ApplicationName
    {
        get { return _ApplicationName; }
        set { _ApplicationName = value; }
    }

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

    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        return false;
    }

    public override iTwitterMembershipUser CreateUser(string login,
                                                      string password,
                                          string email,
                                          string tokenKey,
                                          string tokenSecret,
                                          string twitterUserId,
                                          object providerUserKey,
                                          out MembershipCreateStatus status)
    {
        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(login,
                                                                       password,
                                                                       true);

        OnValidatingPassword(args);

        if (args.Cancel)
        {
            status = MembershipCreateStatus.InvalidPassword;
            return null;
        }

        if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
        {
            status = MembershipCreateStatus.DuplicateEmail;
            return null;
        }

        iTwitterMembershipUser u = GetUser(login, false);

        if (u == null)
        {
            UserRepository _user = new UserRepository();

            _user.CreateUser(login, password, email);
            status = MembershipCreateStatus.Success;

            return GetUser(login, false);
        }
        else
        {
            status = MembershipCreateStatus.DuplicateUserName;
        }

        return null;
    }

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

    public override bool EnablePasswordReset
    {
        get { return _EnablePasswordReset; }
    }

    public override bool EnablePasswordRetrieval
    {
        get { return _EnablePasswordRetrieval; }
    }

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

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        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 string GetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override iTwitterMembershipUser GetUser(string login, bool userIsOnline)
    {
        UserRepository _user = new UserRepository();

        return _user.GetUser(login);
    }

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

    public override string GetUserNameByEmail(string email)
    {
        UserRepository _user = new UserRepository();

        return _user.GetUserNameByEmail(email);
    }

    public override int MaxInvalidPasswordAttempts
    {
        get { return _MaxInvalidPasswordAttempts; }
    }

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { return _MinRequiredNonalphanumericCharacters; }
    }

    public override int MinRequiredPasswordLength
    {
        get { return _MinRequiredPasswordLength; }
    }

    public override int PasswordAttemptWindow
    {
        get { return _PasswordAttemptWindow; }
    }

    public override MembershipPasswordFormat PasswordFormat
    {
        get { return _PasswordFormat; }
    }

    public override string PasswordStrengthRegularExpression
    {
        get { return _PasswordStrengthRegularExpression; }
    }

    public override bool RequiresQuestionAndAnswer
    {
        get { return _RequiresQuestionAndAnswer; }
    }

    public override bool RequiresUniqueEmail
    {
        get { return _RequiresUniqueEmail; }
    }

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

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

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

    public override bool ValidateUser(string login, string password)
    {
        if (login == password)
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    //
    // A helper function to retrieve config values from the configuration file.
    //  

    private string GetConfigValue(string configValue, string defaultValue)
    {
        if (string.IsNullOrEmpty(configValue))
            return defaultValue;

        return configValue;
    }

    //
    // Properties from web.config, default all to False
    //
    private string _ApplicationName;
    private bool _EnablePasswordReset;
    private bool _EnablePasswordRetrieval = false;
    private bool _RequiresQuestionAndAnswer = false;
    private bool _RequiresUniqueEmail = true;
    private int _MaxInvalidPasswordAttempts;
    private int _PasswordAttemptWindow;
    private int _MinRequiredPasswordLength;
    private int _MinRequiredNonalphanumericCharacters;
    private string _PasswordStrengthRegularExpression;
    private MembershipPasswordFormat _PasswordFormat = MembershipPasswordFormat.Hashed;

    public override void Initialize(string name, NameValueCollection config)
    {
        if (config == null)
            throw new ArgumentNullException("config");

        if (name == null || name.Length == 0)
            name = "CustomMembershipProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "Custom Membership Provider");
        }

        base.Initialize(name, config);

        _ApplicationName = GetConfigValue(config["applicationName"],
                      System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
        _MaxInvalidPasswordAttempts = Convert.ToInt32(
                      GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
        _PasswordAttemptWindow = Convert.ToInt32(
                      GetConfigValue(config["passwordAttemptWindow"], "10"));
        _MinRequiredNonalphanumericCharacters = Convert.ToInt32(
                      GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
        _MinRequiredPasswordLength = Convert.ToInt32(
                      GetConfigValue(config["minRequiredPasswordLength"], "6"));
        _EnablePasswordReset = Convert.ToBoolean(
                      GetConfigValue(config["enablePasswordReset"], "true"));
        _PasswordStrengthRegularExpression = Convert.ToString(
                       GetConfigValue(config["passwordStrengthRegularExpression"], ""));

    }
}

iTwitterMembershipUser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using iTwitter.Models;

namespace iTwitter.Models
{
    public class iTwitterMembershipUser : MembershipUser
    {
        private string _tokenKey;
        private string _tokenSecret;
        private string _twitterUserId;
        private string _login;
        private string _email;
        private int _providerUserKey;

        public string tokenKey
        {
            get { return _tokenKey; }
            set { _tokenKey = value; }
        }

        public string tokenSecret
        {
            get { return _tokenSecret; }
            set { _tokenSecret = value; }
        }

        public string twitterUserId
        {
            get { return _twitterUserId; }
            set { _twitterUserId = value; }
        }

        public string login
        {
            get { return _login; }
            set { _login = value; }
        }

        public string email
        {
            get { return _email; }
            set { _email = value; }
        }

        public int providerUserKey
        {
            get { return _providerUserKey; }
            set { _providerUserKey = value; }
        }

        public iTwitterMembershipUser(object providername,
                                  string login,
                                  int providerUserKey,
                                  string email,
                                  string tokenKey,
                                  string tokenSecret,
                                  string twitterUserId)
        {
            this.tokenKey = tokenKey;
            this.tokenSecret = tokenSecret;
            this.twitterUserId = twitterUserId;
            this.login = login;
            this.providerUserKey = providerUserKey;
            this.email = email;
        }




    }
}

webconfig.cs

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->

<configuration>
  <connectionStrings>
  <add name="iTwitterDB" connectionString="metadata=res://*/Models.iTwitter.csdl|res://*/Models.iTwitter.ssdl|res://*/Models.iTwitter.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\iTwitter.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <membership defaultProvider="CustomMembershipProvider">
      <providers>
        <clear />
        <add name="CustomMembershipProvider" type="iTwitterMembershipProvider" connectionStringName="iTwitterDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="iTwitterDB" applicationName="/" />
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="iTwitterDB" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

iTwitterDB :

id int
login varchar(50)
password varchar(100) (MD5 Password Hash)
email varchar(100)
tokenKey varchar(100)
tokenSecret varchar(100)
twitterUserId varchar(100)

UserRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace iTwitter.Models
{
    public class UserRepository
    {
        public iTwitterMembershipUser CreateUser(string login, string password, string email)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                Users user = new Users();

                user.login = login;
                user.email = email;
                user.password = password;
                user.tokenKey = "0";
                user.tokenSecret = "0";
                user.twitterUserId = "0";

                db.AddToUsers(user);
                db.SaveChanges();

                return GetUser(login);
            }
        }

        public string GetUserNameByEmail(string email)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                var result = from u in db.Users where (u.email == email) select u;

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();

                    return dbuser.login;
                }
                else
                {
                    return "";
                }
            }
        }

        public iTwitterMembershipUser GetUser(string login)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                var result = from u in db.Users where (u.login == login) select u;

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();

                    string _login = dbuser.login;
                    int _providerUserKey = dbuser.id;
                    string _email = dbuser.email;
                    string _tokenKey = dbuser.tokenKey;
                    string _tokenSecret = dbuser.tokenSecret;
                    string _twitterUserId = dbuser.twitterUserId;


                    iTwitterMembershipUser user = new iTwitterMembershipUser("CustomMembershipProvider",
                                                              _login,
                                                              _providerUserKey,
                                                              _email,
                                                              _tokenKey,
                                                              _tokenSecret,
                                                              _twitterUserId);

                    return user;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}

我在执行过程中遇到了一些错误编译:

1) 'iTwitterMembershipProvider' 未实现继承的抽象

会员 'System.Web.MembershiProvider.CreateUser(字符串, 字符串,字符串,字符串,字符串,布尔值, 对象,出 System.Web.Security.MembershipCreateStatus)'

2) iTwitterMembershipProvider.CreateUser(字符串,

字符串,字符串,字符串,字符串,布尔值, 对象,出 System.Web.Security.MembershipCreateStatus)': 找不到合适的方法来覆盖

3)'iTwitterMembershipProvider.GetUser(字符串,

bool)':返回类型必须是 'System.Web.Security.MembershipUser' 匹配被覆盖的成员 'System.Web.Security.MembershipProvider.GetUser(字符串, 布尔)'

我被堵在这里了。

谢谢。

I try to implement a Custom MembershipPriver with a Custom MemberShipUser in my own database (with a specifics Users Table Model) :

This is ly diffent files :

iTwitterMembershipProvider.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections.Specialized;
using iTwitter.Models;


 public class iTwitterMembershipProvider : MembershipProvider
{

    public override string ApplicationName
    {
        get { return _ApplicationName; }
        set { _ApplicationName = value; }
    }

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

    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        return false;
    }

    public override iTwitterMembershipUser CreateUser(string login,
                                                      string password,
                                          string email,
                                          string tokenKey,
                                          string tokenSecret,
                                          string twitterUserId,
                                          object providerUserKey,
                                          out MembershipCreateStatus status)
    {
        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(login,
                                                                       password,
                                                                       true);

        OnValidatingPassword(args);

        if (args.Cancel)
        {
            status = MembershipCreateStatus.InvalidPassword;
            return null;
        }

        if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
        {
            status = MembershipCreateStatus.DuplicateEmail;
            return null;
        }

        iTwitterMembershipUser u = GetUser(login, false);

        if (u == null)
        {
            UserRepository _user = new UserRepository();

            _user.CreateUser(login, password, email);
            status = MembershipCreateStatus.Success;

            return GetUser(login, false);
        }
        else
        {
            status = MembershipCreateStatus.DuplicateUserName;
        }

        return null;
    }

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

    public override bool EnablePasswordReset
    {
        get { return _EnablePasswordReset; }
    }

    public override bool EnablePasswordRetrieval
    {
        get { return _EnablePasswordRetrieval; }
    }

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

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        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 string GetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override iTwitterMembershipUser GetUser(string login, bool userIsOnline)
    {
        UserRepository _user = new UserRepository();

        return _user.GetUser(login);
    }

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

    public override string GetUserNameByEmail(string email)
    {
        UserRepository _user = new UserRepository();

        return _user.GetUserNameByEmail(email);
    }

    public override int MaxInvalidPasswordAttempts
    {
        get { return _MaxInvalidPasswordAttempts; }
    }

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { return _MinRequiredNonalphanumericCharacters; }
    }

    public override int MinRequiredPasswordLength
    {
        get { return _MinRequiredPasswordLength; }
    }

    public override int PasswordAttemptWindow
    {
        get { return _PasswordAttemptWindow; }
    }

    public override MembershipPasswordFormat PasswordFormat
    {
        get { return _PasswordFormat; }
    }

    public override string PasswordStrengthRegularExpression
    {
        get { return _PasswordStrengthRegularExpression; }
    }

    public override bool RequiresQuestionAndAnswer
    {
        get { return _RequiresQuestionAndAnswer; }
    }

    public override bool RequiresUniqueEmail
    {
        get { return _RequiresUniqueEmail; }
    }

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

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

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

    public override bool ValidateUser(string login, string password)
    {
        if (login == password)
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    //
    // A helper function to retrieve config values from the configuration file.
    //  

    private string GetConfigValue(string configValue, string defaultValue)
    {
        if (string.IsNullOrEmpty(configValue))
            return defaultValue;

        return configValue;
    }

    //
    // Properties from web.config, default all to False
    //
    private string _ApplicationName;
    private bool _EnablePasswordReset;
    private bool _EnablePasswordRetrieval = false;
    private bool _RequiresQuestionAndAnswer = false;
    private bool _RequiresUniqueEmail = true;
    private int _MaxInvalidPasswordAttempts;
    private int _PasswordAttemptWindow;
    private int _MinRequiredPasswordLength;
    private int _MinRequiredNonalphanumericCharacters;
    private string _PasswordStrengthRegularExpression;
    private MembershipPasswordFormat _PasswordFormat = MembershipPasswordFormat.Hashed;

    public override void Initialize(string name, NameValueCollection config)
    {
        if (config == null)
            throw new ArgumentNullException("config");

        if (name == null || name.Length == 0)
            name = "CustomMembershipProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "Custom Membership Provider");
        }

        base.Initialize(name, config);

        _ApplicationName = GetConfigValue(config["applicationName"],
                      System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
        _MaxInvalidPasswordAttempts = Convert.ToInt32(
                      GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
        _PasswordAttemptWindow = Convert.ToInt32(
                      GetConfigValue(config["passwordAttemptWindow"], "10"));
        _MinRequiredNonalphanumericCharacters = Convert.ToInt32(
                      GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
        _MinRequiredPasswordLength = Convert.ToInt32(
                      GetConfigValue(config["minRequiredPasswordLength"], "6"));
        _EnablePasswordReset = Convert.ToBoolean(
                      GetConfigValue(config["enablePasswordReset"], "true"));
        _PasswordStrengthRegularExpression = Convert.ToString(
                       GetConfigValue(config["passwordStrengthRegularExpression"], ""));

    }
}

iTwitterMembershipUser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using iTwitter.Models;

namespace iTwitter.Models
{
    public class iTwitterMembershipUser : MembershipUser
    {
        private string _tokenKey;
        private string _tokenSecret;
        private string _twitterUserId;
        private string _login;
        private string _email;
        private int _providerUserKey;

        public string tokenKey
        {
            get { return _tokenKey; }
            set { _tokenKey = value; }
        }

        public string tokenSecret
        {
            get { return _tokenSecret; }
            set { _tokenSecret = value; }
        }

        public string twitterUserId
        {
            get { return _twitterUserId; }
            set { _twitterUserId = value; }
        }

        public string login
        {
            get { return _login; }
            set { _login = value; }
        }

        public string email
        {
            get { return _email; }
            set { _email = value; }
        }

        public int providerUserKey
        {
            get { return _providerUserKey; }
            set { _providerUserKey = value; }
        }

        public iTwitterMembershipUser(object providername,
                                  string login,
                                  int providerUserKey,
                                  string email,
                                  string tokenKey,
                                  string tokenSecret,
                                  string twitterUserId)
        {
            this.tokenKey = tokenKey;
            this.tokenSecret = tokenSecret;
            this.twitterUserId = twitterUserId;
            this.login = login;
            this.providerUserKey = providerUserKey;
            this.email = email;
        }




    }
}

webconfig.cs

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->

<configuration>
  <connectionStrings>
  <add name="iTwitterDB" connectionString="metadata=res://*/Models.iTwitter.csdl|res://*/Models.iTwitter.ssdl|res://*/Models.iTwitter.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\iTwitter.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /></connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <membership defaultProvider="CustomMembershipProvider">
      <providers>
        <clear />
        <add name="CustomMembershipProvider" type="iTwitterMembershipProvider" connectionStringName="iTwitterDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear />
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="iTwitterDB" applicationName="/" />
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear />
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="iTwitterDB" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

    <pages>
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

iTwitterDB :

id int
login varchar(50)
password varchar(100) (MD5 Password Hash)
email varchar(100)
tokenKey varchar(100)
tokenSecret varchar(100)
twitterUserId varchar(100)

UserRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace iTwitter.Models
{
    public class UserRepository
    {
        public iTwitterMembershipUser CreateUser(string login, string password, string email)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                Users user = new Users();

                user.login = login;
                user.email = email;
                user.password = password;
                user.tokenKey = "0";
                user.tokenSecret = "0";
                user.twitterUserId = "0";

                db.AddToUsers(user);
                db.SaveChanges();

                return GetUser(login);
            }
        }

        public string GetUserNameByEmail(string email)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                var result = from u in db.Users where (u.email == email) select u;

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();

                    return dbuser.login;
                }
                else
                {
                    return "";
                }
            }
        }

        public iTwitterMembershipUser GetUser(string login)
        {
            using (iTwitterDB db = new iTwitterDB())
            {
                var result = from u in db.Users where (u.login == login) select u;

                if (result.Count() != 0)
                {
                    var dbuser = result.FirstOrDefault();

                    string _login = dbuser.login;
                    int _providerUserKey = dbuser.id;
                    string _email = dbuser.email;
                    string _tokenKey = dbuser.tokenKey;
                    string _tokenSecret = dbuser.tokenSecret;
                    string _twitterUserId = dbuser.twitterUserId;


                    iTwitterMembershipUser user = new iTwitterMembershipUser("CustomMembershipProvider",
                                                              _login,
                                                              _providerUserKey,
                                                              _email,
                                                              _tokenKey,
                                                              _tokenSecret,
                                                              _twitterUserId);

                    return user;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}

I've some error during compilation :

1) 'iTwitterMembershipProvider' does not implement inherited abstract

member
'System.Web.MembershiProvider.CreateUser(string,
string, string, string, string, bool,
object, out
System.Web.Security.MembershipCreateStatus)'

2) iTwitterMembershipProvider.CreateUser(string,

string, string, string, string, bool,
object, out
System.Web.Security.MembershipCreateStatus)':
no suitable method found to override

3)'iTwitterMembershipProvider.GetUser(string,

bool)': return type must be
'System.Web.Security.MembershipUser'
to match overridden member
'System.Web.Security.MembershipProvider.GetUser(string,
bool)'

I'm blocked here.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

树深时见影 2024-11-06 09:31:41

将CreateUser和GetUser的返回类型更改为基类MembershipUser。当您调用这些方法时,您可以将其转换为 iTwitterMembershipUser 类型。例如,在 CreateUser 中,您将 return 语句更改为

return (iTwitterMembershipUser) GetUser(login);

Change the return type of CreateUser and GetUser to the base class MembershipUser. When you call these methods you can then cast it to the type iTwitterMembershipUser. For example in CreateUser you change the return statement to

return (iTwitterMembershipUser) GetUser(login);
三五鸿雁 2024-11-06 09:31:41

我已经很久没有看过MembershipProvider 的东西了,所有的接口我都不记得了。但您的错误在于您正在实现一个抽象基类,该基类具有您未实现的抽象方法。如果您实现一个接口,或者从具有抽象方法的类继承,那么您的类必须提供这些成员的实现。在您的情况下,您的返回类型与抽象方法的返回类型不匹配。

It's been a long time since I looked at the MembershipProvider stuff, and I don't remember all of the interfaces. But your error is in regards to the fact that you are implementing an abstract base class, that has abstract methods that you are not implementing. If you implement an interface, or inherit from a class with abstract methods, then your class must provide implementations of those members. In your case, your return type does not match the return type of the abstract method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文