Sie sind auf Seite 1von 23

ARTCULO

18 6.051
Cmo hacer Login personalizado, registro y cierre de sesin en
EF y MVC usando 4 Razor
Publicado por Raj Kumar en artculos | ASP.NET MVC en 07 de junio de 2013
En este artculo aprenders cmo hacer pantallas de inicio de sesin, registro y cierre de sesin 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 artculo aprenders cmo hacer pantallas de inicio de sesin, registro y cierre de sesin con la funcionalidad del
mundo real utilizando modelos de datos de maquinilla de afeitar y Entity Framework.
Qu es Entity Framework
Entidad marco (EF) es un mapeado objeto-relacional que permite a los desarrolladores .NET trabajar con datos
relacionales usando objetos especficos del dominio. Elimina la necesidad para la mayora del cdigo de acceso a datos
que generalmente los desarrolladores deben escribir. Para ms informacin ver: http://msdn.microsoft.com/en-
us/data/ef.aspx
Qu es MVC?
El patrn Model-View-Controller (MVC) separa el modelado de dominio, la presentacin y las acciones basadas en la
entrada del usuario en tres clases separadas [Burbeck92].
Modelo: el modelo gestiona los datos del dominio de aplicacin y comportamiento, responde a las solicitudes de
informacin 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 visualizacin de informacin.
Controlador: el controlador interpreta las entradas del ratn y el teclado del usuario, informando el modelo o la vista para
cambiar segn 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 "Aplicacin Web ASP.NET MVC 4"
5. Introduzca el nombre y seleccione la ubicacin
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 artculo...
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 cdigo fue generado a partir de una plantilla.
//
Cambios manuales a este archivo pueden producir un comportamiento inesperado en su aplicacin.
Cambios manuales en este fichero se sobrescribirn si el cdigo se regenera.
< / auto-generado >
//------------------------------------------------------------------------------

espacio de nombres LoginInMVC4WithEF.Models
{
usando Sistema;
usando System.Collections.Generic;
usando System.ComponentModel.DataAnnotations;

pblico parcial clase Registro
{
pblico int ID de usuario { obtener; Set; }
[Obligatorio]
[Direccin de correo electrnico]
[StringLength(150)]
[Pantalla(Nombre = "direccin de correo electrnico:")]
pblico cadena Correo electrnico { obtener; Set; }

[Obligatorio]
[Tipo de datos(Tipo de datos.Contrasea)]
[StringLength(150, MinimumLength = 6)]
[Pantalla(Nombre = "contrasea:")]
pblico cadena Contrasea { obtener; Set; }

pblico cadena PasswordSalt { obtener; Set; }

[Obligatorio]
[Pantalla(Nombre = "nombre:")]
pblico cadena Apellido { obtener; Set; }

[Obligatorio]
[Pantalla(Nombre = "nombre:")]
pblico cadena Apellido { obtener; Set; }
pblico cadena UserType { obtener; Set; }
pblico Sistema.Fecha y hora CreatedDate { obtener; Set; }
pblico bool IsActive { obtener; Set; }
pblico cadena Direccin IP { obtener; Set; }
}


Esta es mi clase de contexto, otra vez esto tambin es generada por el modelo de datos.
pblico parcial clase UserEntities2 : DbContext
{
pblico UserEntities2()
: base("nombre = UserEntities2")
{
}

protegido anular vaco OnModelCreating (DbModelBuilder modelBuilder)
{
tiro nuevo UnintentionalCodeFirstException();
}

pblico 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 mtodos.

//
SALIR: /User/
pblico ActionResult Index()
{
volver View();
}

[HttpGet]
pblico ActionResult LogIn()
{
volver View();
}

[HttpPost]
pblico ActionResult LogIn (usuario Models.Registration)
{
Si (ModelState.IsValid)
//{
si (IsValid (usuario.Correo electrnico, usuario.Contrasea))
{
FormsAuthentication.SetAuthCookie (usuario.Correo electrnico falso);
volver RedirectToAction ("Index", "Casa");
}
ms
{
ModelState.AddModelError ("", "los datos de inicio de sesin estn equivocados".);
}
volverView(userr);
}

[HttpGet]
pblico ActionResult Register()
{
volver View();
}

[HttpPost]
pblico 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 electrnico;
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");
}
}
ms
{
ModelState.AddModelError ("", "Datos no estn correctos");
}
}
atrapar (DbEntityValidationException e)
{
foreach (Eva var en e.EntityValidationErrors)
{
Console.WriteLine ("Entidad de tipo \"{0}\"en estado \"{1}\ "tiene los siguientes errores de validacin:",
vspera.Entry.Entity.GetType().Nombre, Eva.Entry.State);
foreach (var View en la vspera.ValidationErrors)
{
Console.WriteLine ("-propiedad: \"{0}\ ", Error: \"{1}\ "",
TelPropertyName, View.ErrorMessage);
}
}
tiro;
}
volverView();
}

pblico ActionResult LogOut()
{
FormsAuthentication.SignOut();
volver RedirectToAction ("Index", "Casa");
}

privado bool IsValid (cadena de correo electrnico, cadena de contrasea)
{
crypto var = new SimpleCrypto.PBKDF2();
bool IsValid = false;

usando (var db = new LoginInMVC4WithEF.Models.UserEntities2())
{
var usuario = db.Registrations.FirstOrDefault (u = > u.Email == Correo electrnico);
si (usuario! = null)
{
si (por el usuario.Contrasea == crypto.Compute (usuario, contrasea.PasswordSalt))
{
IsValid = true;
}
}
}
volver IsValid;
}

Tiene funciones y mtodos de ndice Pgina e inicio de sesin, cierre de sesin, registro y isvalid, ahora vamos hacer algn
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" )
}
ms
{
@ Html.ActionLink ("registro", , "Registrarse" "El usuario" )
< palmo > | < / palmo >
@ Html.ActionLink ("Log en", "Login", "Usuario" )
}
</div>

Ahora vamos a agregar vistas de presentacin.

La mejor manera de agregar una vista es haga clic derecho sobre el nombre del mtodo del controlador y luego con el
botn derecho y "Agregar ver" y seleccionar el motor de vista tipo y seleccione Ver inflexible y use la Pgina principal de
diseo y haga clic en "Add".


Imagen 4.

LogIn.cshtml


@model LoginInMVC4WithEF.Models. Registro

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

< H2 > Inicio de sesin < / 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 >
< 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 >

pblico ActionResult LogOut()
{
FormsAuthentication.SignOut();
volver RedirectToAction ("Index", "Casa");
}


Ahora a F5 para ejecutar la aplicacin y haga clic en el botn "Registrarse" y no poner nada en el TextBbueyes y haga clic
en el botn "Registrar".

Imagen 5.

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

Imagen 6.

Ahora si puse un valor contrasea menos de 6 caracteres o ms 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.

Conclusin
En este artculo hemos aprendido los conceptos bsicos 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/

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.
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-
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: ")]
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]
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)
{
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 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)
@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");
}


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.

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.

Das könnte Ihnen auch gefallen