[英]ASP.Net Setting the correct Connection String when calling Membership.CreateUser()
This is a continuation of my last question: "Internal Database - ASP.NET Auto Web Site Registration on User Creation". 这是我最后一个问题的延续:“内部数据库-用户创建时ASP.NET自动网站注册”。 I am running the following code.
我正在运行以下代码。 This is just a test block of code.
这只是一个测试代码块。 It works but my problem is it creates the default SQLEXPRESS ASPNETDB.MDF in the App_Data Directory.
它有效,但是我的问题是它在App_Data目录中创建了默认的SQLEXPRESS ASPNETDB.MDF。 This is not what I want.
这不是我想要的。
// Create a MembershipCreateStatus Status for Reporting...
MembershipCreateStatus status = new MembershipCreateStatus();
// Setup SqlMembershipProvider for Initialization...
SqlMembershipProvider sqlProvider = new SqlMembershipProvider();
// Setup a NameValueCollection...
NameValueCollection config = new NameValueCollection();
// Set the Connection Name of the SQL Connection String...
string SQLDBNameString = "My Company Database.Properties.Settings.ConnectionString";
// Update the private connection string field in the base class.
string connectionString = "Data Source=Server;Initial Catalog=’My Company Database';User ID=USERNAME;Password=PASSWORD";
// Username of the account to add...
string username = "User121";
// Generate a dynamic Password....
string password = Membership.GeneratePassword(8, 1);
// Email Address of the User...
string email = "email@email.com";
try
{
string Name = "My Company Database";
config.Add("applicationName", "My Company Database");
config.Add("maxInvalidPasswordAttempts", "5");
config.Add("passwordAttemptWindow", "10");
config.Add("minRequiredPasswordLength", "8");
config.Add("passwordStrengthRegularExpression", "");
config.Add("enablePasswordReset", "True");
config.Add("enablePasswordRetrieval", "False");
config.Add("requiresQuestionAndAnswer", "False");
config.Add("requiresUniqueEmail", "True");
config.Add("passwordFormat", "Hashed");
config.Add("connectionStringName", SQLDBNameString);
sqlProvider.Initialize(Name, config);
ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[SQLDBNameString];
if ((ConnectionStringSettings == null) || (ConnectionStringSettings.ConnectionString.Trim() == String.Empty))
{
throw new Exception("Connection string cannot be blank.");
}
// connectionString = ConnectionStringSettings.ConnectionString;
MembershipUser newUser = Membership.CreateUser(username, password, email, "Whats My Password", password, true, out status);
}
catch (Exception ex)
{
String message = "Error...\r\n\r\n" + ex.ToString();
String caption = "Error";
MessageBoxButtons button = MessageBoxButtons.OK;
MessageBoxIcon icon = MessageBoxIcon.Asterisk;
MessageBox.Show(message, caption, button, icon);
}
MessageBox.Show("Account Creation : " + status.ToString() + "\r\n"
+ "Username is : " + username + "\r\n"
+ "Password is : " + password + "\r\n"
+ "Email : " + email);
This code is running in a C# Application, SQL Front end database and it is supposed to automatically create a user so they can login to a web page once I have added them to my database. 此代码在C#应用程序SQL Frontend数据库中运行,并且应该自动创建一个用户,这样,一旦我将他们添加到数据库中,他们就可以登录到网页。 This Code is not running in a ASP Website Application.
该代码未在ASP网站应用程序中运行。 My "config" is not being initalised from what I can see.
从我所看到的来看,我的“配置”没有被初始化。 Any help is much appreaciated!
任何帮助都非常感激!
Finally a solution that works through out my website and C# Internal Database. 最终,一个可以在我的网站和C#内部数据库中运行的解决方案。
A steep learning curve on my part. 我的学习曲线陡峭。 It is actually much simpler than I thought.
实际上,它比我想象的要简单得多。 Here is the Code that needs to go into the app.config file that needs to be in your C# Project:
这是需要进入C#项目中的app.config文件的代码:
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="My Company Database.Properties.Settings.ConnectionString"
connectionString="Data Source=Server;Initial Catalog='My Company Database';Persist Security Info=True;User ID=MyUserName;Password=MyPassword"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="My Company Database.Properties.Settings.ConnectionString"
enablePasswordRetrieval="False" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>
Here is the Code to use the default MembershipProvider(): 这是使用默认MembershipProvider()的代码:
// Create a MembershipCreateStatus Status for Reporting...
MembershipCreateStatus status = new MembershipCreateStatus();
// Username of the account to add...
string username = "User121";
// Generate a dynamic Password....
string password = "P@55W0Rd";
// Email Address of the User...
string email = "email@email.com";
// Password Question of the User...
string passwordQuestion = "My Password Question?";
// Password Answer of the User...
string passwordAnswer = "My Password Answer!";
try
{
Membership.CreateUser(username, password, email, passwordQuestion, passwordAnswer, true, out status);
}
catch (Exception ex)
{
this.richTextBox1.Text = "Error...\r\n\r\n" + ex.ToString();
}
this.richTextBox1.Text = ("Account Creation : " + status.ToString() + "\r\n"
+ "Username is : " + username + "\r\n"
+ "Password is : " + password + "\r\n"
+ "Email : " + email);
I did try to add a web.config the same as the ASP.NET Web Application but this failed. 我确实尝试添加与ASP.NET Web应用程序相同的web.config,但这失败了。 I did not even think of putting the configuration into app.config untill today.
直到今天,我什至没有想到将配置放入app.config中。 Funny how the brain works when trying to solve a problem.
尝试解决问题时大脑的运作方式很有趣。
Password Hashing and Salting is all handled by the default MembershipProvider Class that is built into .NET. 密码哈希和加盐均由.NET内置的默认MembershipProvider类处理。 No need to do any crazy Encoding Hashing and Salting.
无需进行任何疯狂的编码哈希和加盐。
I have this Code working: 我有此代码工作:
// Create MembershipUser...
MembershipUser membershipUser = null;
// Create a MembershipCreateStatus Status for Reporting...
MembershipCreateStatus status = new MembershipCreateStatus();
// Update the private connection string field in the base class.
string connectionString = "Data Source=SERVER;Initial Catalog='My Company Database';User ID=USERNAME;Password=PASSWORD";
// Application Name...
string applicationName = "My Company Database";
// Username of the account to add...
string username = "NewUser";
// Generate a dynamic Password....
string password = Membership.GeneratePassword(12, 3);
// Email Address of the User...
string email = "email@email.com";
// The Password Question...
string passwordQuestion = "What is my Password?";
// The Password Answer...
string passwordAnswer = "My Password is: .....";
// Is Approved...
bool isApproved = true;
// Current Time Utc...
DateTime dateTimeUtc = DateTime.UtcNow;
// Create Date...
DateTime createDateTime = DateTime.Now;
// uniqueEmail =
int uniqueEmail = 1;
// Password Format...
int passwordFormat = 1;
// Set the GUID...
Guid guid= Guid.NewGuid();
if (membershipUser == null)
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand sqlCommand = new SqlCommand("aspnet_Membership_CreateUser", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("@ApplicationName", SqlDbType.NVarChar, 255).Value = applicationName; // Input Parameter...
sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 255).Value = username; // Input Parameter...
sqlCommand.Parameters.Add("@Password", SqlDbType.NVarChar, 127).Value = password; // Input Parameter...
sqlCommand.Parameters.Add("@PasswordSalt", SqlDbType.NVarChar, 127).Value = password; // Input Parameter...
sqlCommand.Parameters.Add("@Email", SqlDbType.NVarChar, 255).Value = email; // Input Parameter...
sqlCommand.Parameters.Add("@PasswordQuestion", SqlDbType.NVarChar, 255).Value = passwordQuestion; // Input Parameter...
sqlCommand.Parameters.Add("@PasswordAnswer", SqlDbType.NVarChar, 127).Value = passwordAnswer; // Input Parameter...
sqlCommand.Parameters.Add("@IsApproved", SqlDbType.Bit).Value = isApproved; // Input Parameter...
sqlCommand.Parameters.Add("@CurrentTimeUtc", SqlDbType.DateTime, 7).Value = dateTimeUtc; // Input Parameter...
sqlCommand.Parameters.Add("@CreateDate", SqlDbType.DateTime, 7).Value = createDateTime; // Input Parameter...
sqlCommand.Parameters.Add("@UniqueEmail", SqlDbType.Int, 3).Value = uniqueEmail; // Input Parameter...
sqlCommand.Parameters.Add("@PasswordFormat", SqlDbType.Int, 3).Value = passwordFormat; // Input Parameter...
sqlCommand.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier, 15).Value = guid; // Output Parameter...
try
{
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
status = MembershipCreateStatus.Success;
}
catch (SqlException ex)
{
richTextBox1.Text = ex.ToString();
status = MembershipCreateStatus.ProviderError;
}
finally
{
sqlConnection.Close();
}
this.textBox1.Text = status.ToString();
The obvious thing is currently I have no checking of Existing User, EMail and so on. 显而易见的事情是,我目前没有检查现有用户,电子邮件等。 I also need to hash the Password Answer and fix the SaltPassword setup.
我还需要哈希密码答案并修复SaltPassword设置。
Here is the Default ASP Provider SQL Stored Procedure for CreateUser: 这是CreateUser的默认ASP提供程序SQL存储过程:
ALTER PROCEDURE [dbo].[aspnet_Membership_CreateUser]
@ApplicationName nvarchar(256),
@UserName nvarchar(256),
@Password nvarchar(128),
@PasswordSalt nvarchar(128),
@Email nvarchar(256),
@PasswordQuestion nvarchar(256),
@PasswordAnswer nvarchar(128),
@IsApproved bit,
@CurrentTimeUtc datetime,
@CreateDate datetime = NULL,
@UniqueEmail int = 0,
@PasswordFormat int = 0,
@UserId uniqueidentifier OUTPUT
AS
BEGIN
DECLARE @ApplicationId uniqueidentifier
SELECT @ApplicationId = NULL
DECLARE @NewUserId uniqueidentifier
SELECT @NewUserId = NULL
DECLARE @IsLockedOut bit
SET @IsLockedOut = 0
DECLARE @LastLockoutDate datetime
SET @LastLockoutDate = CONVERT( datetime, '17540101', 112 )
DECLARE @FailedPasswordAttemptCount int
SET @FailedPasswordAttemptCount = 0
DECLARE @FailedPasswordAttemptWindowStart datetime
SET @FailedPasswordAttemptWindowStart = CONVERT( datetime, '17540101', 112 )
DECLARE @FailedPasswordAnswerAttemptCount int
SET @FailedPasswordAnswerAttemptCount = 0
DECLARE @FailedPasswordAnswerAttemptWindowStart datetime
SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, '17540101', 112 )
DECLARE @NewUserCreated bit
DECLARE @ReturnValue int
SET @ReturnValue = 0
DECLARE @ErrorCode int
SET @ErrorCode = 0
DECLARE @TranStarted bit
SET @TranStarted = 0
IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0
EXEC dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT
IF( @@ERROR <> 0 )
BEGIN
SET @ErrorCode = -1
GOTO Cleanup
END
SET @CreateDate = @CurrentTimeUtc
SELECT @NewUserId = UserId FROM dbo.aspnet_Users WHERE LOWER(@UserName) = LoweredUserName AND @ApplicationId = ApplicationId
IF ( @NewUserId IS NULL )
BEGIN
SET @NewUserId = @UserId
EXEC @ReturnValue = dbo.aspnet_Users_CreateUser @ApplicationId, @UserName, 0, @CreateDate, @NewUserId OUTPUT
SET @NewUserCreated = 1
END
ELSE
BEGIN
SET @NewUserCreated = 0
IF( @NewUserId <> @UserId AND @UserId IS NOT NULL )
BEGIN
SET @ErrorCode = 6
GOTO Cleanup
END
END
IF( @@ERROR <> 0 )
BEGIN
SET @ErrorCode = -1
GOTO Cleanup
END
IF( @ReturnValue = -1 )
BEGIN
SET @ErrorCode = 10
GOTO Cleanup
END
IF ( EXISTS ( SELECT UserId
FROM dbo.aspnet_Membership
WHERE @NewUserId = UserId ) )
BEGIN
SET @ErrorCode = 6
GOTO Cleanup
END
SET @UserId = @NewUserId
IF (@UniqueEmail = 1)
BEGIN
IF (EXISTS (SELECT *
FROM dbo.aspnet_Membership m WITH ( UPDLOCK, HOLDLOCK )
WHERE ApplicationId = @ApplicationId AND LoweredEmail = LOWER(@Email)))
BEGIN
SET @ErrorCode = 7
GOTO Cleanup
END
END
IF (@NewUserCreated = 0)
BEGIN
UPDATE dbo.aspnet_Users
SET LastActivityDate = @CreateDate
WHERE @UserId = UserId
IF( @@ERROR <> 0 )
BEGIN
SET @ErrorCode = -1
GOTO Cleanup
END
END
INSERT INTO dbo.aspnet_Membership
( ApplicationId,
UserId,
Password,
PasswordSalt,
Email,
LoweredEmail,
PasswordQuestion,
PasswordAnswer,
PasswordFormat,
IsApproved,
IsLockedOut,
CreateDate,
LastLoginDate,
LastPasswordChangedDate,
LastLockoutDate,
FailedPasswordAttemptCount,
FailedPasswordAttemptWindowStart,
FailedPasswordAnswerAttemptCount,
FailedPasswordAnswerAttemptWindowStart )
VALUES ( @ApplicationId,
@UserId,
@Password,
@PasswordSalt,
@Email,
LOWER(@Email),
@PasswordQuestion,
@PasswordAnswer,
@PasswordFormat,
@IsApproved,
@IsLockedOut,
@CreateDate,
@CreateDate,
@CreateDate,
@LastLockoutDate,
@FailedPasswordAttemptCount,
@FailedPasswordAttemptWindowStart,
@FailedPasswordAnswerAttemptCount,
@FailedPasswordAnswerAttemptWindowStart )
IF( @@ERROR <> 0 )
BEGIN
SET @ErrorCode = -1
GOTO Cleanup
END
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END
RETURN 0
Cleanup:
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END
RETURN @ErrorCode
END
Seems to me that there is a large limitation in the default MembershipProvider if you want to do simple stuff, like in my case where I wanted to create outside of an ASP Web Application a new User. 在我看来,如果您想做简单的事情,则默认的MembershipProvider会有很大的限制,例如在我想在ASP Web应用程序之外创建新用户的情况下。 Maybe there is another way to do this that is simpler?
也许还有另一种方法可以更简单?
If anyone has a better answer then i would really appreaciate the input? 如果有人有一个更好的答案,那么我真的会增加投入吗?
Thanks. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.