ARTÍCULO

24

Click here to load reader

Transcript of ARTÍCULO

Page 1: ARTÍCULO

ARTÍCULO

18 6.051

Cómo hacer Login personalizado, registro y cierre de sesión en EF y MVC usando 4 Razor Publicado por Raj Kumar en artículos | ASP.NET MVC en 07 de junio de 2013 En este artículo aprenderás cómo hacer pantallas de inicio de sesión, registro y cierre de sesión con la funcionalidad del mundo real utilizando modelos de datos de maquinilla de afeitar y Entity Framework.

inShare0 71703 0 1

Nivel lector:

Descargar archivos:

LoginInMVC4WithEF.zip

En este artículo aprenderás cómo hacer pantallas de inicio de sesión, registro y cierre de sesión con la funcionalidad del mundo real utilizando modelos de datos de maquinilla de afeitar y Entity Framework.

¿Qué es Entity Framework

Page 2: ARTÍCULO

Entidad marco (EF) es un mapeado objeto-relacional que permite a los desarrolladores .NET trabajar con datos relacionales usando objetos específicos del dominio. Elimina la necesidad para la mayoría del código de acceso a datos que generalmente los desarrolladores deben escribir. Para más información ver: http://msdn.microsoft.com/en-us/data/ef.aspx

¿Qué es MVC?

El patrón Model-View-Controller (MVC) separa el modelado de dominio, la presentación y las acciones basadas en la entrada del usuario en tres clases separadas [Burbeck92].

Modelo: el modelo gestiona los datos del dominio de aplicación y comportamiento, responde a las solicitudes de información sobre su estado (generalmente de la vista) y responde a las instrucciones para cambiar el estado (generalmente desde el controlador).

Vista: la vista logra la visualización de información.

Controlador: el controlador interpreta las entradas del ratón y el teclado del usuario, informando el modelo o la vista para cambiar según corresponda.

Getting Started

1. Crear un nuevo proyecto; Primero abra Visual Studio 2012 2. Luego vaya a "File" = > "Nueva" = > "Proyecto..." 3. Seleccione Web en plantillas instaladas 4. Seleccione "Aplicación Web ASP.NET MVC 4"5. Introduzca el nombre y seleccione la ubicación 6. Haga clic en "Aceptar"

Ahora agregar nuevos datos modelo ADO.NET Entity.

Imagen 1.

Para aprender a configurar un ADO.NET Entity Data Model por favor lea este artículo...

Page 3: ARTÍCULO

http://www.c-sharpcorner.com/UploadFile/raj1979/Building-ASP-NET-MVC-Web-Applications-using-ADO-NET-Entity-Data-Model/

Así que procedamos sin perder tiempo, aquí está mi escenario de modelo de datos:

Imagen 2.

Esta es mi clase de modelo que se genera cuando configuramos el modelo de datos, hice los cambios leves.

//------------------------------------------------------------------------------< auto-generado >Este código fue generado a partir de una plantilla.//Cambios manuales a este archivo pueden producir un comportamiento inesperado en su aplicación.Cambios manuales en este fichero se sobrescribirán si el código se regenera.< / auto-generado >//------------------------------------------------------------------------------ espacio de nombres LoginInMVC4WithEF.Models {    usando Sistema;    usando System.Collections.Generic;    usando System.ComponentModel.DataAnnotations;    público parcial clase Registro     {        público int ID de usuario { obtener; Set; }        [Obligatorio][Dirección de correo electrónico]        [StringLength(150)]        [Pantalla(Nombre = "dirección de correo electrónico:")]        público cadena Correo electrónico { obtener; Set; }         [Obligatorio]        [Tipo de datos(Tipo de datos.Contraseña)]        [StringLength(150, MinimumLength = 6)]        [Pantalla(Nombre = "contraseña:")]        público cadena Contraseña { obtener; Set; }         público cadena PasswordSalt { obtener; Set; }         [Obligatorio]

Page 4: ARTÍCULO

        [Pantalla(Nombre = "nombre:")]        público cadena Apellido { obtener; Set; }         [Obligatorio]        [Pantalla(Nombre = "nombre:")]        público cadena Apellido { obtener; Set; }         público cadena UserType { obtener; Set; }        público Sistema.Fecha y hora CreatedDate { obtener; Set; }        público bool IsActive { obtener; Set; }        público cadena Dirección IP { obtener; Set; }   }

 Esta es mi clase de contexto, otra vez esto también es generada por el modelo de datos.público parcial clase UserEntities2 : DbContext {    público UserEntities2()        : base("nombre = UserEntities2")    {    }     protegido anular vacío OnModelCreating (DbModelBuilder modelBuilder)    {        tiro nuevo UnintentionalCodeFirstException();    }     público DbSet <registro> Registro { obtener; Set; }} Ahora para agregar un controlador.

  Imagen 3. Agregar espacios de nombres en la clase de controlador: usando System.Web.Security; usando LoginInMVC4WithEF.Models;

Ahora agregue las siguientes funciones y métodos. //SALIR: /User/público ActionResult Index(){    volver View();}       

Page 5: ARTÍCULO

[HttpGet] público ActionResult LogIn() {    volver View();}        [HttpPost] público ActionResult LogIn (usuario Models.Registration) {Si (ModelState.IsValid)//{    si (IsValid (usuario.Correo electrónico, usuario.Contraseña))    {FormsAuthentication.SetAuthCookie (usuario.Correo electrónico falso);        volver RedirectToAction ("Index", "Casa");    }    más    {ModelState.AddModelError ("", "los datos de inicio de sesión están equivocados".);    }    volverView(userr);}        [HttpGet] público ActionResult Register() {    volver View();} [HttpPost] público ActionResult Registro (usuario Models.Registration){    probar    {        si (ModelState.IsValid)        {            usando (var db = new LoginInMVC4WithEF.Models.UserEntities2())            {crypto var = new SimpleCrypto.PBKDF2();var encrypPass = crypto.Compute (por el usuario.Password);var newUser = db.Registrations.Create();newUser.Email = user.Correo electrónico;newUser.Password = encrypPass;newUser.PasswordSalt = crypto.Sal;newUser.FirstName = user.Apellido;newUser.LastName = user.Apellido;newUser.UserType = "Usuario";newUser.CreatedDate = DateTime.Now;newUser.IsActive = true;newUser.IPAddress = "642 blanco haya Avenue";DB.Registrations.Add(newUser);DB.SaveChanges();                volver RedirectToAction ("Index", "Casa");            }        }        más        {ModelState.AddModelError ("", "Datos no están correctos");        }    }    atrapar (DbEntityValidationException e)

Page 6: ARTÍCULO

    {        foreach (Eva var en e.EntityValidationErrors)        {Console.WriteLine ("Entidad de tipo \"{0}\"en estado \"{1}\ "tiene los siguientes errores de validación:",víspera.Entry.Entity.GetType().Nombre, Eva.Entry.State);            foreach (var View en la víspera.ValidationErrors)            {Console.WriteLine ("-propiedad: \"{0}\ ", Error: \"{1}\ "",TelPropertyName, View.ErrorMessage);            }        }        tiro;    }    volverView();}        público ActionResult LogOut() {FormsAuthentication.SignOut();    volver RedirectToAction ("Index", "Casa");} privado bool IsValid (cadena de correo electrónico, cadena de contraseña){crypto var = new SimpleCrypto.PBKDF2();    bool IsValid = false;     usando (var db = new LoginInMVC4WithEF.Models.UserEntities2())    {var usuario = db.Registrations.FirstOrDefault (u = > u.Email == Correo electrónico);        si (usuario! = null)        {            si (por el usuario.Contraseña == crypto.Compute (usuario, contraseña.PasswordSalt))            {IsValid = true;            }        }    }    volver IsValid;} 

Tiene funciones y métodos de Índice Página e inicio de sesión, cierre de sesión, registro y isvalid, ahora vamos hacer algún cambio en "_Layout.vshtml". Agregue el siguiente div: < div estilo="ancho:auto; color de fondo : Aqua ">        @ si (Request.IsAuthenticated)         {            < fuerte > @ Html.Encode(User.Identity.Name) < / fuerte >            @ Html.ActionLink ("Log a", "Logout", "Usuario" )        }        más        {            @ Html.ActionLink ("registro", , "Registrarse" "El usuario" )            < palmo > | < / palmo >            @ Html.ActionLink ("Log en", "Login", "Usuario" )        }</div> Ahora vamos a agregar vistas de presentación. 

Page 7: ARTÍCULO

La mejor manera de agregar una vista es haga clic derecho sobre el nombre del método del controlador y luego con el botón derecho y "Agregar ver" y seleccionar el motor de vista tipo y seleccione Ver inflexible y use la Página principal de diseño y haga clic en "Add".

  Imagen 4. LogIn.cshtml  @model LoginInMVC4WithEF.Models. Registro @{ViewBag.Title = "LogIn" ;Layout = "~ / Views/Shared/_Layout.cshtml" ;} < H2 > Inicio de sesión < / H2 >@ usando (Html.BeginForm()) {    @ Html.ValidationSummary (verdadero, "Login Failed, compruebe los detalles" );    <div>        <FIELDSET>            < leyenda > Formulario de login < / leyenda >            < div clase= "editor-label" >@Html.LabelFor(u=> u.Email)< /div >            < div clase= "campo editor" >@Html.TextBoxFor(u=> u.Email)                 @Html.ValidationMessageFor (u = > u.Email)            </div>            < div clase= "editor-label" >@Html.LabelFor(u=> u.Password)< /div >

Page 8: ARTÍCULO

            < div clase= "campo editor" >@Html.PasswordFor(u=> u.Password)                 @Html.ValidationMessageFor (u = > usuario.Password)            </div>            < entrada tipo= 'Enviar' valor= "Log In" />        </FIELDSET>    </div>}

Register.cshtml  @model LoginInMVC4WithEF.Models. Registro @{ViewBag.Title = "Registrarse" ;Layout = "~ / Views/Shared/_Layout.cshtml" ;} < H2 > Registro < / H2 >@ usando (Html.BeginForm()) {    @ Html.ValidationSummary (verdadero, "Registeration Failed, campos." );    <div>        <FIELDSET>            < leyenda > Formulario de registro < / leyenda >            < div clase= "editor-label" >@Html.LabelFor(u => u.Email)< /div >            < div clase= "campo editor" >@Html.TextBoxFor(u => u.Email)                 @Html.ValidationMessageFor (u = > u.Email)            </div>            < div clase= "editor-label" >@Html.LabelFor(u => u.Password)< /div >            < div clase= "campo editor" >@Html.PasswordFor(u => u.Password)                 @Html.ValidationMessageFor (u = > usuario.Password)            </div>            < div clase= "editor-label" >@Html.LabelFor(u => u.FirstName)< /div >            < div clase= "campo editor" >@Html.TextBoxFor(u => u.FirstName)                 @Html.ValidationMessageFor (u = > u.FirstName)            </div>             < div clase= "editor-label" >@Html.LabelFor(u => u.LastName)< /div >            < div clase= "campo editor" >@Html.TextBoxFor(u => u.LastName)                 @Html.ValidationMessageFor (u = > u.LastName)            </div>             < entrada tipo= 'Enviar' valor= "Registrarse" />        </FIELDSET>    </div>} LogOut.cshtml  @{ViewBag.Title = "LogOut" ;Layout = "~ / Views/Shared/_Layout.cshtml" ;} < H2 > LogOut < / H2 > público ActionResult LogOut() {FormsAuthentication.SignOut();    volver RedirectToAction ("Index", "Casa");}

Page 9: ARTÍCULO

 Ahora a F5 para ejecutar la aplicación y haga clic en el botón "Registrarse" y no poner nada en el TextBbueyes y haga clic en el botón "Registrar".

Imagen 5. Como se puede ver en la clase de modelo, todos los campos son obligatorios para que estos mensajes se muestran.

Page 10: ARTÍCULO

Imagen 6. Ahora si puse un valor contraseña menos de 6 caracteres o más de 150 personajes se mostrará este mensaje:

Imagen 7. Ahora inserte todos los valores correctamente, entonces usted verá lo registrará y datos deben insertado en la base de datos, ahora se puede acceder.

Imagen 8.

Imagen 9. Conclusión

En este artículo hemos aprendido los conceptos básicos de login usando Entity Framework con navaja.

Pagina

http://www.c-sharpcorner.com/UploadFile/raj1979/how-to-make-custom-login-register-and-logout-in-mvc-4-usin/

Page 11: ARTÍCULO

ARTICLE

18 6,051

How to Make Custom Login, Register, and Logout in MVC 4 Using Razor and EF Posted by Raj Kumar in Articles | ASP.NET MVC on June 07, 2013 In this article you will learn how to make login, register, and logout screens with real-world functionality using Razor and Entity Framework data models.

inShare0 71723 1 1

Reader Level:

Download Files:

LoginInMVC4WithEF.zip

In this article you will learn how to make login, register, and logout screens with real-world functionality using Razor and Entity Framework data models.

Page 12: ARTÍCULO

What is Entity Framework

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write. For more see: http://msdn.microsoft.com/en-us/data/ef.aspx

What is MVC?

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes [Burbeck92].

Model: The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

View: The view manages the display of information.

Controller: The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

Getting Started

1. Create a new project; first open Visual Studio 2012 2. Then go to "File" => "New" => "Project..." 3. Select Web in installed templates 4. Select "ASP.NET MVC 4 Web Application"5. Enter the name and choose the location 6. Click "OK"

Now add a new ADO.NET Entity data Model.

Image 1.

To learn how to configure an ADO.NET Entity Data Model please read this article-

Page 13: ARTÍCULO

http://www.c-sharpcorner.com/uploadfile/raj1979/building-Asp-Net-mvc-web-applications-using-ado-net-entity-data-model/

So let's proceed without wasting time, here is my data model scenario:

Image 2.

This is my model class that is generated when we configure the data model, I just made slight changes.

//------------------------------------------------------------------------------// <auto-generated>//    This code was generated from a template.////    Manual changes to this file may cause unexpected behavior in your application.//    Manual changes to this file will be overwritten if the code is regenerated.// </auto-generated>//------------------------------------------------------------------------------ namespace LoginInMVC4WithEF.Models{    using System;    using System.Collections.Generic;    using System.ComponentModel.DataAnnotations;        public partial class Registration    {        public int UserId { get; set; }        [Required]        [EmailAddress]        [StringLength(150)]        [Display(Name = "Email Address: ")]        public string Email { get; set; }         [Required]        [DataType(DataType.Password)]        [StringLength(150, MinimumLength = 6)]        [Display(Name = "Password: ")]        public string Password { get; set; }         public string PasswordSalt { get; set; }         [Required]        [Display(Name = "First Name: ")]

Page 14: ARTÍCULO

        public string FirstName { get; set; }         [Required]        [Display(Name = "Last Name: ")]        public string LastName { get; set; }         public string UserType { get; set; }        public System.DateTime CreatedDate { get; set; }        public bool IsActive { get; set; }        public string IPAddress { get; set; }   }

 This is my context class, again this is also generated by data model.public partial class UserEntities2 : DbContext{    public UserEntities2()        : base("name=UserEntities2")    {    }     protected override void OnModelCreating(DbModelBuilder modelBuilder)    {        throw new UnintentionalCodeFirstException();    }     public DbSet<Registration> Registrations { get; set; }} Now to add a controller.

  Image 3. Add namespaces in the controller class: using System.Web.Security;using LoginInMVC4WithEF.Models;

Now add the following functions and methods. //// GET: /User/public ActionResult Index(){    return View();}        [HttpGet]       

Page 15: ARTÍCULO

public ActionResult LogIn(){    return View();}        [HttpPost]        public ActionResult LogIn(Models.Registration userr){//if (ModelState.IsValid)//{    if (IsValid(userr.Email, userr.Password))    {        FormsAuthentication.SetAuthCookie(userr.Email, false);        return RedirectToAction("Index", "Home");    }    else    {        ModelState.AddModelError("", "Login details are wrong.");    }    return View(userr);}        [HttpGet]        public ActionResult Register(){    return View();} [HttpPost]      public ActionResult Register(Models.Registration user){    try    {        if (ModelState.IsValid)        {            using (var db = new LoginInMVC4WithEF.Models.UserEntities2())            {                var crypto = new SimpleCrypto.PBKDF2();                var encrypPass = crypto.Compute(user.Password);                var newUser = db.Registrations.Create();                newUser.Email = user.Email;                newUser.Password = encrypPass;                newUser.PasswordSalt = crypto.Salt;                newUser.FirstName = user.FirstName;                newUser.LastName = user.LastName;                newUser.UserType = "User";                newUser.CreatedDate = DateTime.Now;                newUser.IsActive = true;                newUser.IPAddress = "642 White Hague Avenue";                db.Registrations.Add(newUser);                db.SaveChanges();                return RedirectToAction("Index", "Home");            }        }        else        {            ModelState.AddModelError("", "Data is not correct");        }    }    catch (DbEntityValidationException e)    {

Page 16: ARTÍCULO

        foreach (var eve in e.EntityValidationErrors)        {            Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",                eve.Entry.Entity.GetType().Name, eve.Entry.State);            foreach (var ve in eve.ValidationErrors)            {                Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",                    ve.PropertyName, ve.ErrorMessage);            }        }        throw;    }    return View();}        public ActionResult LogOut(){    FormsAuthentication.SignOut();    return RedirectToAction("Index", "Home");} private bool IsValid(string email, string password){    var crypto = new SimpleCrypto.PBKDF2();    bool IsValid = false;     using (var db = new LoginInMVC4WithEF.Models.UserEntities2())    {        var user = db.Registrations.FirstOrDefault(u => u.Email == email);        if (user != null)        {            if (user.Password == crypto.Compute(password, user.PasswordSalt))            {                IsValid = true;            }        }    }    return IsValid;} 

There I have functions and methods for index page and login, logout, register and isvalid, now let's make some change in "_Layout.vshtml". Add the following div: <div style="width:auto; background-color:aqua">        @if (Request.IsAuthenticated)        {            <strong>@Html.Encode(User.Identity.Name)</strong>            @Html.ActionLink("Log Out", "Logout", "User")        }        else        {            @Html.ActionLink("Register", "Register", "User")            <span> | </span>            @Html.ActionLink("Log In", "Login", "User")        }</div> Now let's add views for presentation. The best way to add a view is to right-click on the controller's method name and then right-click and "Add

Page 17: ARTÍCULO

View" and select the view engine type and select strongly-typed view and use the layout master page and click "Add".

  Image 4. LogIn.cshtml  @model LoginInMVC4WithEF.Models.Registration @{    ViewBag.Title = "LogIn";    Layout = "~/Views/Shared/_Layout.cshtml";} <h2>LogIn</h2>@using (Html.BeginForm()){    @Html.ValidationSummary(true, "Login Failed, check details");    <div>        <fieldset>            <legend>Login Form</legend>            <div class="editor-label">@Html.LabelFor(u=> u.Email)</div>            <div class="editor-field">@Html.TextBoxFor(u=> u.Email)                @Html.ValidationMessageFor(u=> u.Email)            </div>            <div class="editor-label">@Html.LabelFor(u=> u.Password)</div>            <div  class="editor-field">@Html.PasswordFor(u=> u.Password)

Page 18: ARTÍCULO

                @Html.ValidationMessageFor(u=> u.Password)            </div>            <input type="submit" value="Log In" />        </fieldset>    </div>}

Register.cshtml  @model LoginInMVC4WithEF.Models.Registration@{    ViewBag.Title = "Register";    Layout = "~/Views/Shared/_Layout.cshtml";} <h2>Register</h2>@using (Html.BeginForm()){    @Html.ValidationSummary(true, "Registeration Failed, fields.");    <div>        <fieldset>            <legend>Register Form</legend>            <div class="editor-label">@Html.LabelFor(u => u.Email)</div>            <div class="editor-field">@Html.TextBoxFor(u => u.Email)                @Html.ValidationMessageFor(u => u.Email)            </div>            <div class="editor-label">@Html.LabelFor(u => u.Password)</div>            <div class="editor-field">@Html.PasswordFor(u => u.Password)                @Html.ValidationMessageFor(u => u.Password)            </div>            <div class="editor-label">@Html.LabelFor(u => u.FirstName)</div>            <div class="editor-field">@Html.TextBoxFor(u => u.FirstName)                @Html.ValidationMessageFor(u => u.FirstName)            </div>             <div class="editor-label">@Html.LabelFor(u => u.LastName)</div>            <div class="editor-field">@Html.TextBoxFor(u => u.LastName)                @Html.ValidationMessageFor(u => u.LastName)            </div>             <input type="submit" value="Register" />        </fieldset>    </div>} LogOut.cshtml  @{    ViewBag.Title = "LogOut";    Layout = "~/Views/Shared/_Layout.cshtml";} <h2>LogOut</h2> public ActionResult LogOut(){    FormsAuthentication.SignOut();    return RedirectToAction("Index", "Home");}

Page 19: ARTÍCULO

 Now hit F5 to run the application and click on the "Register" button and don't put anything in the TextBoxes and click the "Register" button.

Image 5. As you can see in the model class, all fields are required so these messages are displayed.

Page 20: ARTÍCULO

Image 6. Now if I put a password value less than 6 characters or more than 150 characters then this message will display:

Image 7. Now insert all values properly, then you will see it will register and data should inserted into the database, now you can login.

Image 8.

Image 9. Conclusion

In this article we have learned the basic concepts of login using Entity Framework with Razor.