Posts

Showing posts from June, 2018

MVC Forms Authentication - Basic

// // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } /* Add code to query the database for valid user or not */ if (validUser) { FormsAuthentication.SetAuthCookie(model.Email, false); var authTicket = new FormsAuthenticationTicket(1, model.Email, DateTime.Now, DateTime.Now.AddMinutes(20), false, ""); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Response.Cookies.Add(authCookie); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() {     FormsA...

MVC Forms Authentication with Custom Membership

MVC Forms Authentication and Storing Data in the Cookie Introduction Forms authentication is a common feature in many C# MVC .NET web applications. There are a variety of methods for implementing forms authentication in MVC .NET. A key part for each, is the process of storing user specific details that are carried throughout the web application. User details such as Id, Username, Address, and Age may be obtained through various methods, such as by querying the database upon every request or as needed, loading from cache, context, or even loading from Session. In this tutorial, we’ll walk through the steps of implementing forms authentication in C# MVC .NET, specifically with MVC4. We’ll use a custom MembershipProvider class, along with a custom Principal object. The Principal will hold our custom user details, encrypted within the forms authentication ticket cookie, and allow us to access this data anywhere within the web application. Setting up the Web.Config for Forms Aut...

Entity Framework Code First steps:

Entity Framework Code First steps: 1. Create a Context class which is a subclass of DbContext using System.Data.Entity; namespace MovieStore.Models { public class MovieStoreContext : DbContext { public DbSet<Customer> Customers { get; set; } public DbSet<Movie> Movies { get; set; } } } 2. Add a connection string in the web.config file <connectionStrings> <add name=" MovieStoreContext " connectionString="Data Source=HOUDEV206D\MSSQLSERVER08;Initial Catalog=SportsStore;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> Imp : The connection string name and the Context class name must be the same. If no connection string is specified in the web.config file a new database file(.mdf) will be created under the App_Data folder. 3. Run the following commands in Package Manager Console: a. enable-migrations b. add-migration 'InitialModel' c. update-databas...