articles

Working with SimpleMembership in ASP.NET MVC

Anonymous User11893 23-Jan-2015

Hi everyone in this article I’m explaining about simplemembership, role, websecurity etc.

Description:

This article describes how to use SimpleMembership of WebMatrix.Authenication and authorization that is a very necessary part of web applications. SimpleMembership, introduced with WebMatrix, tries to address these issues by offering a flexible model for authenticating users.

Authentication and authorization are commonly needed features in any modern web application. ASP.NET 2.0 introduced membership and role management through the provider model. Although the default membership and role providers work well in many situations, they are quite rigid in terms of database schema and the way they store user information in the database. For example, while using the default membership provider you don't have much control on the table in which user names (login names) are stored. This rigidity creates difficulties in situations where user login information needs to be stored in a table with custom schema or in situations where authentication is happening via some third party (OAuth based authentication for example).

It relies on the core membership and roles provider of ASP.NET but wraps them in an easy to use and flexible way. Have a look at the following figure that shows the inheritance hierarchy of SimpleMembership.

WebMatrix.WebData assembly contains two important classes, viz. SimpleMembershipProvider and SimpleRoleProvider. The SimpleMembershipProvider class inherits from the ExtendedMembershipProvider class that in turn inherits from the MembershipProvider class residing in the System.Web.Security namespace. The SimpleRoleProvider class inherits directly from the RoleProvider class from the System.Web.Security namespace. 

Start:

Open visual studio >> File >> New Project >> Select ASP.NET MVC Web Application

Working with SimpleMembership in ASP.NET MVC

Give application name and click ok

After click ok window open like this and select empty template

Working with SimpleMembership in ASP.NET MVC

Install some packages like this

1.      Install entity frame work from Manage NuGet Package

Working with SimpleMembership in ASP.NET MVC

And then install entityframe work

 Working with SimpleMembership in ASP.NET MVC


2. Install DotNetOpenAuth package from Manage NuGet Package

 

Working with SimpleMembership in ASP.NET MVC

 3. Install Microsoft.AspNet.Web.Optimization

 

Working with SimpleMembership in ASP.NET MVC

 4. Install Microsoft.AspNet.WebPages.Data


 Working with SimpleMembership in ASP.NET MVC


5. Install Microsoft.AspNet.WebPages.OAuth


 Working with SimpleMembership in ASP.NET MVC


6. Download these scripts for validation and use bootstrap menu


Working with SimpleMembership in ASP.NET MVC

7. Download latest bootstrap package for good look and feel 


In this sample we use local database for manage login and register

You can use this connection string in web.config

<connectionStrings>
    <addname="DefaultConnection"connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-LoginAuthnticationSample-20150122181727;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-LoginAuthnticationSample-20150122181727.mdf"providerName="System.Data.SqlClient" />
  </connectionStrings>

 

Now we can add 2 new class inside “App_Start” folder:


1.      AuthConfig.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.WebPages.OAuth;
using LoginAuthnticationSample.Models;
 
namespace LoginAuthnticationSample
{
    publicstaticclassAuthConfig
    {
        publicstaticvoid RegisterAuth()
        {
           
        }
    }
}


 2. BundleConfig.cs 

using System.Web;
using System.Web.Optimization;
 
namespace LoginAuthnticationSample
{
    publicclassBundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        publicstaticvoid RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(newScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
 
            bundles.Add(newScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
 
            bundles.Add(newScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
 
            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(newScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));
 
            bundles.Add(newStyleBundle("~/Content/css").Include("~/Content/site.css"));
 
            bundles.Add(newStyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
        }
    }
}

 

Now we can add HomeController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace LoginAuthnticationSample.Controllers
{
    publicclassHomeController : Controller
    {
        publicActionResult Index()
        {
            return View();
        }
    }
}

 

Now we can add AccountModels:

 

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
 
namespace LoginAuthnticationSample.Models
{
    publicclassUsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }
 
        publicDbSet<UserProfile> UserProfiles { get; set; }
    }
 
    [Table("UserProfile")]
    publicclassUserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        publicint UserId { get; set; }
        publicstring UserName { get; set; }
    }
 
    publicclassLocalPasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        publicstring OldPassword { get; set; }
 
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        publicstring NewPassword { get; set; }
 
        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        publicstring ConfirmPassword { get; set; }
    }
 
    publicclassLoginModel
    {
        [Required]
        [Display(Name = "User name")]
        publicstring UserName { get; set; }
 
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        publicstring Password { get; set; }
 
        [Display(Name = "Remember me?")]
        publicbool RememberMe { get; set; }
    }
 
    publicclassRegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        publicstring UserName { get; set; }
 
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        publicstring Password { get; set; }
 
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        publicstring ConfirmPassword { get; set; }
    }
 
}

 

Now we can add AccountController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using LoginAuthnticationSample.Filters;
using LoginAuthnticationSample.Models;
 
namespace LoginAuthnticationSample.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    publicclassAccountController : Controller
    {
        //
        // GET: /Account/Login
 
        [AllowAnonymous]
        publicActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
 
        //
        // POST: /Account/Login
 
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        publicActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToLocal(returnUrl);
            }
 
            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
 
        //
        // POST: /Account/LogOff
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        publicActionResult LogOff()
        {
            WebSecurity.Logout();
 
            return RedirectToAction("Index", "Home");
        }
 
        //
        // GET: /Account/Register
 
        [AllowAnonymous]
        publicActionResult Register()
        {
            return View();
        }
 
        //
        // POST: /Account/Register
 
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        publicActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }
 
            // If we got this far, something failed, redisplay form
            return View(model);
        }
 
        //
        // POST: /Account/Disassociate
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        publicActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;
 
            // Only disassociate the account if the currently logged in user is the owner
            if (ownerAccount == User.Identity.Name)
            {
                // Use a transaction to prevent the user from deleting their last login credential
                using (var scope = newTransactionScope(TransactionScopeOption.Required, newTransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }
 
            return RedirectToAction("Manage", new { Message = message });
        }
 
        //
        // GET: /Account/Manage
 
        publicActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }
 
        //
        // POST: /Account/Manage
 
        [HttpPost]
        [ValidateAntiForgeryToken]
        publicActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // ChangePassword will throw an exception rather than return false in certain failure scenarios.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }
 
                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                    }
                }
            }
            else
            {
                // User does not have a local password so remove any validation errors caused by a missing
                // OldPassword field
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }
 
                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception e)
                    {
                        ModelState.AddModelError("", e);
                    }
                }
            }
 
            // If we got this far, something failed, redisplay form
            return View(model);
        }
 
        #region Helpers
        privateActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
 
        publicenumManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }
 
        privatestaticstring ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                caseMembershipCreateStatus.DuplicateUserName:
                    return"User name already exists. Please enter a different user name.";
 
                caseMembershipCreateStatus.DuplicateEmail:
                    return"A user name for that e-mail address already exists. Please enter a different e-mail address.";
 
                caseMembershipCreateStatus.InvalidPassword:
                    return"The password provided is invalid. Please enter a valid password value.";
 
                caseMembershipCreateStatus.InvalidEmail:
                    return"The e-mail address provided is invalid. Please check the value and try again.";
 
                caseMembershipCreateStatus.InvalidAnswer:
                    return"The password retrieval answer provided is invalid. Please check the value and try again.";
 
                caseMembershipCreateStatus.InvalidQuestion:
                    return"The password retrieval question provided is invalid. Please check the value and try again.";
 
                caseMembershipCreateStatus.InvalidUserName:
                    return"The user name provided is invalid. Please check the value and try again.";
 
                caseMembershipCreateStatus.ProviderError:
                    return"The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
 
                caseMembershipCreateStatus.UserRejected:
                    return"The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
 
                default:
                    return"An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}

 

Now we can add new Folder “Filter”

Make new class “InitializeSimpleMembershipAttribute.cs

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using LoginAuthnticationSample.Models;
 
namespace LoginAuthnticationSample.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    publicsealedclassInitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        privatestaticSimpleMembershipInitializer _initializer;
        privatestaticobject _initializerLock = newobject();
        privatestaticbool _isInitialized;
 
        publicoverridevoid OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }
 
        privateclassSimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);
 
                try
                {
                    using (var context = newUsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
 
                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    thrownewInvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
}

 

Now we can add view of account

1.     Login.cshtml

@model LoginAuthnticationSample.Models.LoginModel
 
@{
    ViewBag.Title = "Log in";
}
 
<br/>
<br/>
<br/>
<divclass="row">
    <divclass="col-md-8 col-md-offset-2 well">
        @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            <h2class="text-center">Login</h2>
            <hr/>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "ID" })
                        @Html.ValidationMessageFor(m => m.UserName)
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Password" })
                        @Html.ValidationMessageFor(m => m.Password)
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <spanclass="pull-left"style="margin-top:8px;">@Html.CheckBoxFor(m => m.RememberMe)&nbsp;&nbsp;</span><spanclass="pull-left">@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })</span>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <inputtype="submit"value="Login"class="form-control btn btn-info"/>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <pclass="text-center">
                @Html.ActionLink("Register", "Register") if you don't have an account.
            </p>
            <divclass="clearfix">&nbsp;</div>
        }
    </div>
</div>
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


 2. Register.cshtml 

@model LoginAuthnticationSample.Models.RegisterModel
@{
    ViewBag.Title = "Register";
}
 
<br/>
<br/>
<br/>
<divclass="row">
    <divclass="col-md-8 col-md-offset-2 well">
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary()
            <h2class="text-center">Register</h2>
            <hr/>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "User name" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.Password, new { @class = "form-control", @placeholder = "Password" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", @placeholder = "Confirm password" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <inputtype="submit"value="Register"class="form-control btn btn-info"/>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="clearfix">&nbsp;</div>
        }
    </div>
</div>
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

 3. Manage.cshtml 

@model LoginAuthnticationSample.Models.LocalPasswordModel
@{
    ViewBag.Title = "Manage Account";
}
 
<pclass="message-success">@ViewBag.StatusMessage</p>
 
<p>You're logged in as <strong>@User.Identity.Name</strong>.</p>
 
@if (ViewBag.HasLocalPassword)
{
    @Html.Partial("_ChangePasswordPartial")
}
else
{
    @Html.Partial("_SetPasswordPartial")
}
 
 
 
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

 4. _ChangePasswordPartial.cshtml 

@model LoginAuthnticationSample.Models.LocalPasswordModel
 
<br/>
<br/>
<br/>
<divclass="row">
    <divclass="col-md-8 col-md-offset-2 well">
        @using (Html.BeginForm("Manage", "Account"))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary()
            <h2class="text-center">Change Password</h2>
            <hr/>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-user"></i>
                        </span>
                        @Html.PasswordFor(m => m.OldPassword, new { @class = "form-control", @placeholder = "OldPassword" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.NewPassword, new { @class = "form-control", @placeholder = "New Password" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="input-group">
                        <spanclass="input-group-addon">
                            <iclass="glyphicon glyphicon-lock"></i>
                        </span>
                        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control", @placeholder = "Confirm password" })
                    </div>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="row">
                <divclass="col-md-12">
                    <inputtype="submit"value="Save"class="form-control btn btn-info"/>
                </div>
            </div>
            <divclass="clearfix">&nbsp;</div>
            <divclass="clearfix">&nbsp;</div>
        }
    </div>
</div>

 5. _SetPasswordPartial .cshtml 

@model LoginAuthnticationSample.Models.LocalPasswordModel
 
<p>
    You do not have a local password for this site. Add a local
    password so you can log in without an external login.
</p>
 
@using (Html.BeginForm("Manage", "Account")) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
 
    <fieldset>
        <legend>Set Password Form</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.NewPassword)
                @Html.PasswordFor(m => m.NewPassword)
            </li>
            <li>
                @Html.LabelFor(m => m.ConfirmPassword)
                @Html.PasswordFor(m => m.ConfirmPassword)
            </li>
        </ol>
        <inputtype="submit"value="Set password"/>
    </fieldset>
}

 Add Layout page inside shared folder:

<!DOCTYPEhtml>
<htmllang="en">
<head>
    <metacharset="utf-8"/>
    <title>@ViewBag.Title - My ASP.NET MVC Application</title>
    <linkhref="~/favicon.ico"rel="shortcut icon"type="image/x-icon"/>
    <metaname="viewport"content="width=device-width"/>
    <linkhref="~/Content/bootstrap/css/bootstrap.min.css"rel="stylesheet"/>
    <linkhref="~/Content/bootstrap/css/bootstrap-tag-cloud.css"rel="stylesheet"/>
 
    <scriptsrc="~/Scripts/jquery-2.1.1.min.js"></script>
    <scriptsrc="~/Scripts/bootstrap/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            $(function () {
                $("#myCarousel").carousel({
                    interval: 5000
                });
            });
        });
    </script>
</head>
<body>
    <divclass="navbar navbar-default navbar-fixed-top">
        <divclass="container">
            <divclass="navbar-header">
                <buttontype="button"class="navbar-toggle"data-toggle="collapse"data-target=".navbar-collapse">
                    <spanclass="icon-bar"></span>
                    <spanclass="icon-bar"></span>
                    <spanclass="icon-bar"></span>
                </button>
                @Html.ActionLink("Mindstick", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <divclass="navbar-collapse collapse">
                <ulclass="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "")</li>
                    <li>@Html.ActionLink("About", "")</li>
                    <li>@Html.ActionLink("Contact", "")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <br/>
    <br/>
    <br/>
    <divclass="container"id="body">
        <divclass="row">
            @RenderSection("featured", required: false)
            <divclass="col-md-8">
                @RenderBody()
            </div>
            <divclass="col-md-4">
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <h3class="panel-title"><iclass="glyphicon glyphicon-tags"></i>Tags</h3>
                    </div>
                    <divclass="panel-body">
                        <ulid="tag-cloud"style="padding: 0; margin: 0;">
                            <liclass="tag-cloud tag-cloud-warning">blog</li>
                            <liclass="tag-cloud tag-cloud-warning">footer</li>
                            <liclass="tag-cloud tag-cloud-warning">user interface</li>
                            <liclass="tag-cloud tag-cloud-warning">user</li>
                            <liclass="tag-cloud tag-cloud-warning">post</li>
                            <liclass="tag-cloud tag-cloud-warning">edit</li>
                        </ul>
                    </div>
                </div>
                <divclass="clearfix">&nbsp;</div>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <h3class="panel-title"><iclass="glyphicon glyphicon-pencil"></i>Recent Activity</h3>
                    </div>
                    <divclass="panel-body">
                        <ulclass="list-group">
                            <liclass="list-group-item">Added New Article</li>
                            <liclass="list-group-item">Added New Blog</li>
                            <liclass="list-group-item">Added New Interview</li>
                            <liclass="list-group-item">Porta ac consectetur ac</li>
                            <liclass="list-group-item">Vestibulum at eros</li>
                        </ul>
                    </div>
                </div>
                <divclass="clearfix">&nbsp;</div>
                <divclass="panel panel-default">
                    <divclass="panel-heading">
                        <h3class="panel-title"><iclass="glyphicon glyphicon-pencil"></i>Top 5 Rankers</h3>
                    </div>
                    <divclass="panel-body">
                        <divid="myCarousel"class="carousel slide">
                            <divclass="carousel-inner">
                                <divclass="item active">
                                    <imgsrc="/Images/1.jpg"class="thumbnail"style="height: 50px; height: 50px; margin: 0auto;">
                                </div>
                                <divclass="item">
                                    <imgsrc="/Images/2.jpg"class="thumbnail"style="height: 50px; height: 50px; margin: 0auto;">
                                </div>
                                <divclass="item">
                                    <imgsrc="/Images/3.jpg"class="thumbnail"style="height: 50px; height: 50px; margin: 0auto;">
                                </div>
                                <divclass="item text-center">
                                    <imgsrc="/Images/4.jpg"class="thumbnail"style="height: 50px; height: 50px; margin: 0auto;">
                                </div>
                                <divclass="item">
                                    <imgsrc="/Images/5.jpg"class="thumbnail"style="height: 50px; height: 50px; margin: 0auto;">
                                </div>
                            </div>
                            <aclass="left carousel-control"href="#myCarousel"data-slide="prev">
                                <spanclass="icon-prev"></span>
                            </a>
                            <aclass="right carousel-control"href="#myCarousel"data-slide="next">
                                <spanclass="icon-next"></span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

 

Add _LoginPartial page inside shared folder:

 

@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
    {
        <ulclass="nav navbar-nav navbar-right">
 
            <li>@Html.ActionLink(User.Identity.Name, "Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })</li>
            @Html.AntiForgeryToken()
            <li><ahref="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
 
        </ul>
    }
}
else
{
    <ulclass="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

 

Add Error.cshtml page inside shared folder:

 

@model System.Web.Mvc.HandleErrorInfo
 
@{
    ViewBag.Title = "Error";
}
 
<hgroupclass="title">
    <h1class="error">Error.</h1>
    <h2class="error">An error occurred while processing your request.</h2>
</hgroup>

 

Add _ViewStart.cshtml:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

 

Note: Add Index view of HomeController because our application run on by default setting in RouteConfig.cs file

 

Output:

When application run first time

 Working with SimpleMembership in ASP.NET MVC

Output:

When click on login

Working with SimpleMembership in ASP.NET MVC

After login

Working with SimpleMembership in ASP.NET MVC

Output:

If you want to change password click on user name

Working with SimpleMembership in ASP.NET MVC

 

 

Output:

Create new user click on Register

Working with SimpleMembership in ASP.NET MVC


In my previous post i'll explain about Working with SQLite database


I am a content writter !

Leave Comment

Comments

Liked By