We can use the ASP.NET membership provider in WinForms
application using the following way.
1.
Create ASP.NET membership database using
aspnet_regsql.exe which is location at Windows\Microsoft.NET\Framework\{.NET
version} directory.
2.
Configure the app.config file as follows
<configuration>
<connectionStrings>
<add name="UserDbConnectionString" connectionString="FullConnectionString" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="UserDbConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" cacheRolesInCookie="true" createPersistentCookie="false" cookieProtection="All">
<providers>
<remove name="AspNetSqlRoleProvider"/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" applicationName="AspNet" connectionStringName="UserDbConnectionString"/>
</providers>
</roleManager>
</system.web>
</configuration>
3.
Add project references
i)
System.Security
ii)
System.Web
iii)
System.Web.ApplicationServices
4.
Now you can use code like below
i.
Create User
private void btnCreate_Click(object sender, EventArgs e)
{
try
{
MembershipUser user;
user = Membership.CreateUser(txtUser.Text,
txtPass.Text);
MessageBox.Show(txtUser.Text + "is created successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
ii.
Validate User
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (Membership.ValidateUser(txtUser.Text,
txtPass.Text))
{
var roles = Roles.GetRolesForUser(txtUser.Text);
}
else
{
MessageBox.Show(txtUser.Text + " is failed to login.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}