Esta es una aplicación MVC desarrollada con .NET Framework 4.8 para fines de aprendizaje.
Resultados de la acción
| Tipo | Método auxiliar |
|---|---|
| ViewResult | Vista() |
| ParcialviewResult | Parcialview () |
| ContentResult | Contenido() |
| Redirectivo | Redireccionar () |
| Redirecttoruteresult | RedirectToAction () |
| Jonresultor | Json () |
| Fileresult | Archivo() |
| HttpnotfoundResult | Httpnotfound () |
| Vacío | - |
algunos ejemplos
public ActionResult Test ( )
{
return View ( data ) ;
return Content ( "Hello World!" ) ;
return HttpNotFound ( ) ;
return new EmptyResult ( ) ;
return RedirectToAction ( "Index" , "Home" , new { page = "1" , sortBy = "name" } ) ;
} Enrutamiento basado en convenciones: en RouteConfig.cs
routes . MapRoute (
"MoviesByReleaseDate" , //name of route
"movies/released/{year}/{month}" , //route url
new { controller = "Movies" , action = "ByReleaseDate" } , //default corresponding controller and actions
new { year = @"2020|2021" , month = @"d{2}" } ) ; //constraints for parameters Enrutamiento de atributos : en ruteconfig.cs Agregar routes.MapMvcAttributeRoutes(); Antes del controlador, use el atributo [Route("url template")] . También se pueden usar restricciones como Min, Max, MinLength, MaxLength, Int, Float, GUID.
[ Route ( "movies/released/{year:regex( \ d{4}:range(1800,2021))}/{month:regex( \ d{2}:range(1,12))}" ) ]
public ActionResult ByReleaseDate ( int year , int month )
{
return Content ( year + "/" + month ) ;
} public ActionResult Test ( )
{
var movie = new Movie ( ) { Name = "Shrek!" } ;
ViewData [ "Movie" ] = movie ;
ViewBag . Movie = movie ;
return View ( movie ) ;
} < h2 > @Model.Name </ h2 > <!-- preffered way -->
< h2 > @( ((Movie) ViewData["Movie"]).Name) </ h2 > <!-- ugly way / dont use -->
< h2 > @ViewBag.Movie.Name </ h2 > <!-- casted at runtime / not safe --> public class RandomMovieViewModel
{
public Movie Movie { get ; set ; }
public List < Customer > Customers { get ; set ; }
} public class MoviesController : Controller
{
// GET: Movies
public ActionResult Random ( )
{
//adding data
var movie = new Movie ( ) { Name = "Shrek!" } ;
var customers = new List < Customer >
{
new Customer { Name = "cust1" } ,
new Customer { Name = "cust2" }
} ;
//filing viewmodel with data
var viewModel = new RandomMovieViewModel ( )
{
Movie = movie ,
Customers = customers
} ;
return View ( viewModel ) ;
}@ *
this is a razor comment
* @
@ {
//multiple lines
//when razor sees html prints it and when razor sees csharp interprets it
}
@ {
var className = Model . Customers . Count > 0 ? "popular" : null ;
}
< h2 class = "@className" > @Model . Movie . Name < / h2 > < ! -- preferred way -- >
@if ( Model . Customers . Count == 0 )
{
< p > No one has rented this movie before . < / p >
}
< ul >
@foreach ( var customer in Model . Customers )
{
< li > @customer . Name < / li >
}
< / ul > Cree la vista en las vistas como vista y seleccione Vista parcial. Uso en otras vistas @Html.Partial("_PartialView", Model.Data)




Marco de entidad: un ORM que mapea los datos en una base de datos relacional a nuestros objetos mediante el archivo de contexto.
LINQ: Método como consultas SQL.
Flujos de trabajo: base de datos primero, código primero.
DB Primero: Diseñe las tablas de la base de datos primero, luego deje que EF genere clases de dominio de acuerdo con las tablas.
Código primero: cree clases de dominio primero, luego deje que EF genere tablas de bases de datos para nosotros.
DBSET al nombre de la tabla en contexto: clase dbcontext en la consola de administrador de paquetes PM > enable-migrations , PM> add-migration migrationName , PM> update-database
Sembrando DB: Pon comandos SQL en un método de migraciones up ()
en controlador
private Context _context ;
public CustomersController ( )
{
_context = new Context ( ) ;
}
//...
public ActionResult Index ( )
{
var customers = _context . Customers . ToList ( ) ;
return View ( customers ) ;
}
//...
public ActionResult Details ( int id )
{
var customer = _context . Customers . Single ( c => c . Id == id ) ;
return View ( customer ) ;
} Cargar tabla extranjera relacional : _context.Customer.Include(c=>c.MembershipType).ToList();





En la vista:
@using ( Html . BeginForm ( actionName : "Create" , controllerName : "Customers" ) )
{
< div class = "form-group" >
@Html . LabelFor ( m => m . Name )
@Html . TextBoxFor ( m => m . Name , new { @class = "form-control" } )
< / div >
} en modelo con anotación de datos:
[ Display ( Name = "Date of Birth" ) ]
public DateTime ? Birthdate { get ; set ; } o en la vista con <label for="Birthdate">Date of Birth</label>
Crea ViewModel:
public class NewCustomerViewModel
{
public IEnumerable < MembershipType > MembershipTypes { get ; set ; }
public Customer Customer { get ; set ; }
}En el controlador:
var membershipTypes = _context . MembershipTypes . ToList ( ) ;
var viewModel = new NewCustomerViewModel ( )
{
MembershipTypes = membershipTypes
} ;En la vista:
< div class =" form-group " >
@Html.LabelFor(m = > m.Customer.MembershipTypeId)
@Html.DropDownListFor(m = > m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes,"Id","Name"),"Select Membership Type", new { @class = "form-control" })
</ div > En el controlador:
[ HttpPost ]
public ActionResult Create ( Customer customer )
{
//...
return View ( ) ;
}En la vista, asegúrese de nombre de acción y nombre del controlador
( Html . BeginForm ( actionName : "Create" , controllerName : "Customers" ) )
//... [ HttpPost ]
public ActionResult Create ( Customer customer )
{
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
return RedirectToAction ( "Index" , "Customers" ) ;
} Llene los datos con el elemento correspondiente del ID en el controlador:
public ActionResult Edit ( int id )
{
var customer = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customer == null )
return HttpNotFound ( ) ;
var viewModel = new CustomerFormViewModel ( )
{
Customer = customer ,
MembershipTypes = _context . MembershipTypes . ToList ( )
} ;
return View ( "CustomerForm" , viewModel ) ;
}
} Si no existe, si existe, si existe. En el controlador mapa los atributos
public ActionResult Save ( Customer customer )
{
if ( customer . Id == 0 )
_context . Customers . Add ( customer ) ;
else
{
var customerInDb = _context . Customers . Single ( c => c . Id == customer . Id ) ;
customerInDb . Name = customer . Name ;
customerInDb . Birthdate = customer . Birthdate ;
customerInDb . MembershipTypeId = customer . MembershipTypeId ;
customerInDb . IsSubscribedToNewsletter = customer . IsSubscribedToNewsletter ;
}
_context . SaveChanges ( ) ;
return RedirectToAction ( "Index" , "Customers" ) ;
}Agregue el campo de identificación dependiente a la vista como oculto:
@Html.HiddenFor(m= > m.Customer.Id)


Paso 1: Agregar anotaciones en el modelo, Paso 2: Agregar control de validación en el controlador. Cuando no es un formulario de retorno válido con los datos de los usuarios
if ( ! ModelState . IsValid )
{
var viewModel = new CustomerFormViewModel
{
Customer = customer ,
MembershipTypes = _context . MembershipTypes . ToList ( )
} ;
return View ( "CustomerForm" , viewModel ) ;
}Paso 3: Agregar mensaje de validación para ver:
@Html.ValidationMessageFor(m= > m.Customer.Name)Error de validación de estilo acceder a estas clases y estilizar:
. field-validation-error {
color : red;
}
. input-validation-error {
border : 2 px red;
}Mensaje de validación primordial en el modelo Agregue esto a la anotación de datos requerida
[ Required ( ErrorMessage = "Please enter customer's name." ) ]
[ StringLength ( 255 ) ]
public string Name { get ; set ; } Paso1: cree una clase que herede la validaciónAttribute (usando System.ComponentModel.DataAntations)
public class Min18YearsIfAMember : ValidationAttribute
{
protected override ValidationResult IsValid ( object value , ValidationContext validationContext )
{
var customer = ( Customer ) validationContext . ObjectInstance ;
if ( customer . MembershipTypeId == 0 || customer . MembershipTypeId == 1 )
{
return ValidationResult . Success ;
}
if ( customer . Birthdate == null )
{
return new ValidationResult ( "Birthdate is required." ) ;
}
var age = DateTime . Today . Year - customer . Birthdate . Value . Year ;
return ( age >= 18 )
? ValidationResult . Success
: new ValidationResult ( "Customer should be at least 18 years old to go on a membership." )
}
}Paso 2: Agregar anotación de datos al modelo
[ Display ( Name = "Membership Type" ) ]
[ Min18YearsIfAMember ]
public byte MembershipTypeId { get ; set ; }Paso 3: Agregar mensaje a la vista
@Html.ValidationMessageFor(m= > m.Customer.MembershipTypeId)@Html.ValidationSummary(true, "Please fix the following errors.")ExcludPropertYerrors: Verdadero Mensaje de listado de errores individuales: el mensaje que se muestra al usuario (podría ser estilizado)
Agregue esto a los formularios a la vista
@section scripts {
@Scripts . Render ( "~/bundles/jqueryval" )
} En vistas, use este ayudante HTML:
@Html . AntiForgeryToken ( )y en la acción del controlador Agregue esta anotación de datos:
En los controladores, cree una API web y agregue esto a global.asax.js:
GlobalConfiguration . Configure ( WebApiConfig . Register ) ;En el contexto de inicializar el controlador:
private Context _context ;
public CustomersController ( )
{
_context = new Context ( ) ;
}Crear métodos Get/Post/Put como: Obtener todo:
//GET /api/customers
[ HttpGet ]
public IEnumerable < Customer > GetCustomers ( )
{
return _context . Customers . ToList ( ) ;
}Obtenga uno:
//GET /api/customers/1
[ HttpGet ]
public Customer GetCustomer ( int id )
{
var customer = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customer == null )
throw new HttpResponseException ( HttpStatusCode . NotFound ) ;
return customer ;
}Crear:
//POST /api/customers
[ HttpPost ]
public Customer CreateCustomer ( Customer customer )
{
if ( ! ModelState . IsValid )
throw new HttpResponseException ( HttpStatusCode . BadRequest ) ;
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
return customer ;
}Actualizar:
//PUT /api/customers/1
[ HttpPut ]
public void UpdateCustomer ( int id , Customer customer )
{
if ( ! ModelState . IsValid )
throw new HttpResponseException ( HttpStatusCode . BadRequest ) ;
var customerInDb = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customerInDb == null )
throw new HttpResponseException ( HttpStatusCode . NotFound ) ;
customerInDb . Name = customer . Name ;
customerInDb . Birthdate = customer . Birthdate ;
customerInDb . IsSubscribedToNewsletter = customer . IsSubscribedToNewsletter ;
customerInDb . MembershipTypeId = customer . MembershipTypeId ;
_context . SaveChanges ( ) ;
}Borrar:
//DELETE /api/customers/1
[ HttpDelete ]
public void DeleteCustomer ( int id )
{
var customerInDb = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customerInDb == null )
throw new HttpResponseException ( HttpStatusCode . NotFound ) ;
_context . Customers . Remove ( customerInDb ) ;
_context . SaveChanges ( ) ;
}Prueba con cartero
Objetos de dominio que eliminamos los datos que no queremos que se cambien o se muestren. Formado para nuestras necesidades. Almacenar en la carpeta DTOS
En app_start, cree mappingprofile.cs:
public class MappingProfile : Profile
{
public MappingProfile ( )
{
Mapper . CreateMap < Customer , CustomerDto > ( ) ;
Mapper . CreateMap < CustomerDto , Customer > ( ) ;
}
}Agregar mapper a global.asax.cs
protected void Application_Start ( )
{
Mapper . Initialize ( c => c . AddProfile < MappingProfile > ( ) ) ;
//..
}Actualización de acciones del controlador:
//GET /api/customers
[ HttpGet ]
public IEnumerable < CustomerDto > GetCustomers ( )
{
return _context . Customers . ToList ( ) . Select ( Mapper . Map < Customer , CustomerDto > ) ;
} //GET /api/customers/1
[ HttpGet ]
public CustomerDto GetCustomer ( int id )
{
var customer = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customer == null )
throw new HttpResponseException ( HttpStatusCode . NotFound ) ;
return Mapper . Map < Customer , CustomerDto > ( customer ) ;
} //POST /api/customers
[ HttpPost ]
public CustomerDto CreateCustomer ( CustomerDto customerDto )
{
if ( ! ModelState . IsValid )
throw new HttpResponseException ( HttpStatusCode . BadRequest ) ;
var customer = Mapper . Map < CustomerDto , Customer > ( customerDto ) ;
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
customerDto . Id = customer . Id ;
return customerDto ;
} //PUT /api/customers/1
[ HttpPut ]
public void UpdateCustomer ( int id , CustomerDto customerDto )
{
if ( ! ModelState . IsValid )
throw new HttpResponseException ( HttpStatusCode . BadRequest ) ;
var customerInDb = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customerInDb == null )
throw new HttpResponseException ( HttpStatusCode . NotFound ) ;
Mapper . Map ( customerDto , customerInDb ) ;
_context . SaveChanges ( ) ;
} en app_start webapiconfig.cs Agregar en registro
var settings = config . Formatters . JsonFormatter . SerializerSettings ;
settings . ContractResolver = new CamelCasePropertyNamesContractResolver ( ) ;
settings . Formatting = Formatting . Indented ; Resultados correctos de HTTP para nuestras acciones:
//GET /api/customers/1
[ HttpGet ]
public IHttpActionResult GetCustomer ( int id )
{
var customer = _context . Customers . SingleOrDefault ( c => c . Id == id ) ;
if ( customer == null )
return NotFound ( ) ;
return Ok ( Mapper . Map < Customer , CustomerDto > ( customer ) ) ;
} //POST /api/customers
[ HttpPost ]
public IHttpActionResult CreateCustomer ( CustomerDto customerDto )
{
if ( ! ModelState . IsValid )
return BadRequest ( ) ;
var customer = Mapper . Map < CustomerDto , Customer > ( customerDto ) ;
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
customerDto . Id = customer . Id ;
return Created ( new Uri ( Request . RequestUri + "/" + customer . Id ) , customerDto ) ;
} Postman: Get: https: // localhost: 44362/api/películas 200 ok
[
{
"id" : 1 ,
"name" : " Citizen Kane " ,
"genreId" : 3 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1941-01-01T00:00:00 " ,
"numberInStock" : 4
},
{
"id" : 3 ,
"name" : " Rear Window " ,
"genreId" : 10 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1954-01-01T00:00:00 " ,
"numberInStock" : 3
},
//.......
]Get: https: // localhost: 44362/api/películas/7 200 ok
{
"id" : 7 ,
"name" : " The Good, the Bad and the Ugly " ,
"genreId" : 6 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1966-01-01T00:00:00 " ,
"numberInStock" : 1
}Publicación: https: // localhost: 44362/api/películas 201 creado
{
"name" : " Life Is Beautiful " ,
"genreId" : 3 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1997-01-01T00:00:00 " ,
"numberInStock" : 1
}Put: https: // localhost: 44362/api/películas/11 204 sin contenido
{
"name" : " Life Is Beautiful " ,
"genreId" : 3 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1997-01-01T00:00:00 " ,
"numberInStock" : 5
}Eliminar: https: // localhost: 44362/api/películas/12 204 sin contenido
En la vista, Agregar clases, datos e ID a elementos. Y al final del guión:
< table id =" customers " < ---
class =" table table-borderless " >
< tr class =" danger " >
< th > Customers </ th >
....
....
< td >
< button data-customer-id =" @item.Id " < ---
class =" btn-link js-delete " < ---
>
Delete
</ button >
</ td >
.....
@section scripts{
< script >
$ ( document ) . ready ( function ( ) {
$ ( "#customers .js-delete" ) . on ( "click" , function ( ) {
var button = $ ( this ) ;
if ( confirm ( "sure to delete?" ) ) {
$ . ajax ( {
url : "/api/customers/" + button . attr ( "data-customer-id" ) ,
method : "DELETE" ,
success : function ( ) {
alert ( "success" ) ;
button . parents ( "tr" ) . remove ( ) ;
}
} ) ;
}
} ) ;
} ) ;
</ script >
} Agregue bundleconfig.cs:
bundles . Add ( new ScriptBundle ( "~/bundles/bootstrap" ) . Include (
"~/Scripts/bootstrap.js" ,
"~/Scripts/bootbox.js" , //<--- here
"~/Scripts/respond.js"
) ) ;Implementar a la vista:
@section scripts{
< script >
$ ( document ) . ready ( function ( ) {
$ ( "#customers .js-delete" ) . on ( "click" , function ( ) {
var button = $ ( this ) ;
bootbox . confirm ( "sure to delete?" , function ( result ) {
if ( result ) {
$ . ajax ( {
url : "/api/customers/" + button . attr ( "data-customer-id" ) ,
method : "DELETE" ,
success : function ( ) {
alert ( "success" ) ;
button . parents ( "tr" ) . remove ( ) ;
}
} ) ;
}
} ) ;
} ) ;
} ) ;
</ script >
} Agregue a los paquetes: (y fusionamos los paquetes de terceros a lib. En _Layout.cshtml -> @Scripts.Render("~/bundles/lib") ))
bundles . Add ( new ScriptBundle ( "~/bundles/lib" ) . Include (
"~/Scripts/jquery-{version}.js" ,
"~/Scripts/bootstrap.js" ,
"~/Scripts/bootbox.js" ,
"~/Scripts/respond.js" ,
"~/Scripts/DataTables/jquery.dataTables.js" , //<--
"~/Scripts/DataTables/dataTables.bootstrap.js" //<--
) ) ; bundles . Add ( new StyleBundle ( "~/Content/css" ) . Include (
"~/Content/bootstrap.css" ,
"~/content/datatables/css/dataTables.bootstrap.css" , //<-- style
"~/Content/site.css" ) ) ;En la vista, las tablas deben tener ID y thead, etiquetas Tbody. Por último, en la sección de script cuando se prepara el documento:
$ ( document ) . ready ( function ( ) {
$ ( "#customers" ) . DataTable ( ) ;
//...
} En jQuery dataTable Llamar:
$ ( document ) . ready ( function ( ) {
$ ( "#customers" ) . DataTable ( {
ajax : {
url : "/api/customers" ,
dataSrc : ""
} ,
columns : [
{
data : "name" ,
render : function ( data , type , customer ) {
return "<a href='/customers/edit/'" + customer . id + "'>" + customer . name ;
}
} ,
{
data : "membershipType.name"
} ,
{
data : "id" ,
render : function ( data ) {
return "<button class='btn-link js-delete' data-customer-id=" + data + ">Delete</button>" ;
}
}
]
} ) ; Paso 1: Cree DTO, Paso 2: Agregue DTO al Paso de DTO Paso 3. Mapas en Perfil de mapeo Paso 4: Agregar al controlador (._appdbContext.customers.include (c => c.MemberShipType) .tolist () ..) Paso 5: Agregue la columna como:
{
data : "membershipType.name"
} , Asigne la tabla a la variable y úsela en el método eliminar:
< script >
$ ( document ) . ready ( function ( ) {
var table //<--
= $ ( "#customers" ) . DataTable ( {
ajax : {
url : "/api/customers" ,
dataSrc : ""
} ,
columns : [
{
data : "name" ,
render : function ( data , type , customer ) {
return "<a href='/customers/edit/'" + customer . id + "'>" + customer . name ;
}
} ,
{
data : "membershipType.name"
} ,
{
data : "id" ,
render : function ( data ) {
return "<button class='btn-link js-delete' data-customer-id=" + data + ">Delete</button>" ;
}
}
]
} ) ;
$ ( "#customers" ) . on ( "click" , ".js-delete" , function ( ) {
var button = $ ( this ) ;
bootbox . confirm ( "Are you sure you want to delete this customer?" , function ( result ) {
if ( result ) {
$ . ajax ( {
url : "/api/customers/" + button . attr ( "data-customer-id" ) ,
method : "DELETE" ,
success : function ( ) {
///<--- here
table . row ( button . parents ( "tr" ) )
. remove ( ) . draw ( ) ;
}
} ) ;
}
} ) ;
} ) ;
} ) ;
</ script > 
Toda la lógica viene incorporada (ver Commit para archivos y detalles)
Agregar atributo [autorizar] a las acciones del controlador o en la parte superior del controlador para restringir todas las acciones
FilterConfig.cs:
filters . Add ( new AuthorizeAttribute ( ) ) ;Esto deshabilita todos los controladores para usuarios no autorizados, pero puede agregar [allowanonymous] a controladores o acciones para habilitar el acceso
Sembrar la base de datos : para mantener la consistencia del proyecto en diferentes escenarios de trabajo, agrégalos a una migración
Crear vistas separadas para invitados y usuarios autorizados
En el controlador:
public ViewResult Index ( int ? pageIndex , string sortBy )
{
if ( User . IsInRole ( RoleName . CanManageMovies ) )
return View ( "List" ) ;
return View ( "ReadOnlyList" ) ;
} Para deshabilitar otras acciones de acceso Agregue este atributo: [Authorize(Roles = RoleName.CanManageMovies)]
Cree un modelo para mantener roles rolename.cs:
public const string CanManageMovies = "CanManageMovies" ; Para agregar campos personalizados al usuario: agregue el accesorio a la clase de usuario de la aplicación y viewModel de la vista. también agregue el nuevo accesorio para registrar la sección de asignación de acciones
Habilitar SSL en propiedades, agregar filtro
filters . Add ( new RequireHttpsAttribute ( ) ) ;Obtenga APPID y AppSecret de Facebook, Google ... Inserte en startup.auth.cs
app . UseFacebookAuthentication (
appId : "id" ,
appSecret : "secret" ) ;Agregue cualquier accesorio personalizado al formulario de inicio de sesión externo y ViewModel. Inicializar en el controlador de inicio de sesión externo

En Nuget install Glimpse.mvc5 y Glimpse.ef6 vaya a /glimse.axd y habilitar
Deshabilitar el almacenamiento en caché: [OutputCache(Duration = 0, VaryByParam = "*", NoStore = true)]
Habilitar el almacenamiento en caché:
[OutputCache(Duration=50,Location=OutputCacheLocation.Server,VaryByParam="genre")]
en acción del controlador
if ( MemoryCache . Default [ "Genres" ] == null )
{
MemoryCache . Default [ "Genres" ] = _appDbContext . Genres . ToList ( ) ;
}
var genres = MemoryCache . Default [ "Genres" ] as IEnumerable < Genre > ; en web.config en System.web
Vamos a agregar una función de alquiler a nuestra aplicación Crear DTO: NewRentalDTO:
public class NewRentalDto
{
public int CustomerId { get ; set ; }
public List < int > MovieIds { get ; set ; }
}Crear modelo: alquiler, agregar al contexto y ejecutar una migración
public class Rental
{
public int Id { get ; set ; }
[ Required ]
public Customer Customer { get ; set ; }
[ Required ]
public Movie Movie { get ; set ; }
public DateTime DateRented { get ; set ; }
public DateTime ? DateReturned { get ; set ; }
}Más detalles sobre comodos. (Usado Typeehead, Bloodhound para autocompletar)
Haga clic derecho y publique
PM> update-database -script -SourceMigration:SeedUsers
MIG objetivo para durar. Tienes una consulta SQL de tu DB ahora
en Web.Config <appSettings key="value"></appSettings> o crea externamente otro archivo de configuración <appSettings configSource="AppSettings.config"></appSettings> Use en código como: ConfigurationManager.AppSettings["Key"] Nota: Appsettings siempre devuelve las condiciones. Necesitas convertirlo para tus necesidades manualmente
en web.config agregar a <system.web>
<customErrors mode="On"></customErrors>
ON: Habilitar en todas partes Remoto: Desactivar en Localhost
Personalizar en Vistas> Error compartido.cshtml
en Web.Config Agregar a <system.web> >> <customErrors>
< system .web>
< customErrors mode = " On " >
< error statusCode = " 404 " redirect = " ~/404.html " />
</ customErrors >
<!-- ..... -->
</ system .web> n web.config Agregar a <system.webServer>
< httpErrors errorMode = " Custom " >
< remove statusCode = " 404 " />
< error statusCode = " 404 " path = " 404.html " responseMode = " File " />
</ httpErrors >Custom: Habilitar en todas partes detallado Localonly: Deshabilitar en localhost
Nuget> Elmah
EXCECCIÓN LOGGER. acceso por /elmah.axd
Por defecto, guarda registros a la memoria, pero con una pequeña configuración podríamos tener estas excepciones en todo tipo de bases de datos.
para acceder a su remota a Elmah
< authorization >
< allow roles = " admin,user2,user3,... " />
< deny users = " * " />
</ authorization >¡¡¡GRACIAS!!!