Este é um aplicativo MVC desenvolvido com o .NET Framework 4.8 para fins de aprendizado.
Resultados da ação
| Tipo | Método Helper |
|---|---|
| ViewResult | Visualizar() |
| ParcialViewResult | ParcialView () |
| ContentResult | Contente() |
| RedirectResult | Redirecionar () |
| Redirecttorouteresult | RedirectToAction () |
| JSONRESULT | JSON () |
| FILERESULT | Arquivo() |
| HttpnotfoundResult | Httpnotfound () |
| Esvaziar | - |
Alguns exemplos
public ActionResult Test ( )
{
return View ( data ) ;
return Content ( "Hello World!" ) ;
return HttpNotFound ( ) ;
return new EmptyResult ( ) ;
return RedirectToAction ( "Index" , "Home" , new { page = "1" , sortBy = "name" } ) ;
} Routing baseado em convenções: em 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 Roteamento de atributo : no routeConfig.cs Add routes.MapMvcAttributeRoutes(); Antes do controlador, use o atributo [Route("url template")] . Também restrições como min, max, minlength, maxlength, int, float, guid podem ser usadas.
[ 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 > Crie visualização em visualizações como visualização e selecione Visualização parcial. Uso em outra visualização @Html.Partial("_PartialView", Model.Data)




Framework de entidade: um ORM que mapeia os dados em um banco de dados relacional para nossos objetos usando o arquivo de contexto.
LINQ: Método como consultas SQL.
Fluxos de trabalho: Banco de dados Primeiro, código primeiro.
DB First: Design Tabels Database Primeiro, depois deixe o EF gerar classes de domínio de acordo com as tabelas.
Código Primeiro: Crie classes de domínio primeiro, mais tarde deixe o EF gerar tabelas de banco de dados para nós.
DBSET para tabela Nome no Contexto: DBContext Classe no Console do Gerenciador de Pacotes PM > enable-migrations , PM> add-migration migrationName , PM> update-database
DB de semeadura: Coloque os comandos SQL em um método de migrações UP ()
no 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 ) ;
} Carregar tabela estranha relacional : _context.Customer.Include(c=>c.MembershipType).ToList();





em 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 >
} No modelo com anotação de dados:
[ Display ( Name = "Date of Birth" ) ]
public DateTime ? Birthdate { get ; set ; } ou em vista com <label for="Birthdate">Date of Birth</label>
Crie ViewModel:
public class NewCustomerViewModel
{
public IEnumerable < MembershipType > MembershipTypes { get ; set ; }
public Customer Customer { get ; set ; }
}no controlador:
var membershipTypes = _context . MembershipTypes . ToList ( ) ;
var viewModel = new NewCustomerViewModel ( )
{
MembershipTypes = membershipTypes
} ;em 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 > no controlador:
[ HttpPost ]
public ActionResult Create ( Customer customer )
{
//...
return View ( ) ;
}Em vista, certifique -se do nome da ação e do nome do controlador
( Html . BeginForm ( actionName : "Create" , controllerName : "Customers" ) )
//... [ HttpPost ]
public ActionResult Create ( Customer customer )
{
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
return RedirectToAction ( "Index" , "Customers" ) ;
} Preencha os dados com o item correspondente do ID no 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 ) ;
}
} Se não existe, adicione, se existir atualização. No mapa do controlador, os 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" ) ;
}Adicione o campo de identificação dependente em vista como oculto:
@Html.HiddenFor(m= > m.Customer.Id)


Etapa 1: Adicione anotações no modelo, Etapa 2: Adicione controle de validação no controlador. Quando não não é válido de retorno do formulário de usuários
if ( ! ModelState . IsValid )
{
var viewModel = new CustomerFormViewModel
{
Customer = customer ,
MembershipTypes = _context . MembershipTypes . ToList ( )
} ;
return View ( "CustomerForm" , viewModel ) ;
}Etapa 3: Adicione a mensagem de validação para visualizar:
@Html.ValidationMessageFor(m= > m.Customer.Name)Erro de validação de estilo Acesse estas classes e estilizar:
. field-validation-error {
color : red;
}
. input-validation-error {
border : 2 px red;
}Mensagem de validação substituta no modelo Adicione isso à anotação de dados necessária
[ Required ( ErrorMessage = "Please enter customer's name." ) ]
[ StringLength ( 255 ) ]
public string Name { get ; set ; } Etapa 1: Crie uma classe que herde a validaçãoTtribute (usando o System.comPonentModel.DataAnnotações)
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." )
}
}Etapa2: Adicione a anotação de dados ao modelo
[ Display ( Name = "Membership Type" ) ]
[ Min18YearsIfAMember ]
public byte MembershipTypeId { get ; set ; }Etapa 3: Adicione mensagem para visualizar
@Html.ValidationMessageFor(m= > m.Customer.MembershipTypeId)@Html.ValidationSummary(true, "Please fix the following errors.")excludePropertyErrors: True oculta Mensagem de listagem de erros individuais: A mensagem exibida para o usuário (poderia ser estilizada)
Adicione isso aos formulários em exibição
@section scripts {
@Scripts . Render ( "~/bundles/jqueryval" )
} Nas vistas, use este ajudante HTML:
@Html . AntiForgeryToken ( )e na ação do controlador Adicione esta anotação de dados:
Nos controladores, crie uma API da Web e adicione isso ao global.asax.js:
GlobalConfiguration . Configure ( WebApiConfig . Register ) ;No contexto inicial do controlador:
private Context _context ;
public CustomersController ( )
{
_context = new Context ( ) ;
}Crie métodos Get/Post/Put como: Get All:
//GET /api/customers
[ HttpGet ]
public IEnumerable < Customer > GetCustomers ( )
{
return _context . Customers . ToList ( ) ;
}Pegue um:
//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 ;
}Criar:
//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 ;
}Atualizar:
//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 ( ) ;
}Excluir:
//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 ( ) ;
}Teste com Postman
Objetos de domínio que removemos os dados que não queremos ser alterados ou mostrados. Moldado para nossas necessidades. Armazene na pasta DTOS
Em App_Start Create MappingProfile.cs:
public class MappingProfile : Profile
{
public MappingProfile ( )
{
Mapper . CreateMap < Customer , CustomerDto > ( ) ;
Mapper . CreateMap < CustomerDto , Customer > ( ) ;
}
}Adicione o mapeador ao global.asax.cs
protected void Application_Start ( )
{
Mapper . Initialize ( c => c . AddProfile < MappingProfile > ( ) ) ;
//..
}Atualizar ações do 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 ( ) ;
} Em App_Start WebApiconfig.cs Adicionar no Registro
var settings = config . Formatters . JsonFormatter . SerializerSettings ;
settings . ContractResolver = new CamelCasePropertyNamesContractResolver ( ) ;
settings . Formatting = Formatting . Indented ; Resultados corretos do HTTP para nossas ações:
//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/filmes 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/filmes/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
}Post: https: // localhost: 44362/api/filmes 201 criado
{
"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/filmes/11 204 Sem conteúdo
{
"name" : " Life Is Beautiful " ,
"genreId" : 3 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1997-01-01T00:00:00 " ,
"numberInStock" : 5
}Delete: https: // localhost: 44362/api/filmes/12 204 Sem conteúdo
Em vista, adicione aulas, dados e ID aos itens. E no script final:
< 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 >
} Adicione BundleConfig.cs:
bundles . Add ( new ScriptBundle ( "~/bundles/bootstrap" ) . Include (
"~/Scripts/bootstrap.js" ,
"~/Scripts/bootbox.js" , //<--- here
"~/Scripts/respond.js"
) ) ;implementar em 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 >
} Adicione aos pacotes: (e mesclamos pacotes @Scripts.Render("~/bundles/lib") terceiros para 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" ) ) ;Na vista, as tabelas devem ter identificação e tead, tags TBody. Por fim, na seção de scripts quando o documento pronto:
$ ( document ) . ready ( function ( ) {
$ ( "#customers" ) . DataTable ( ) ;
//...
} na chamada jQuery datatable:
$ ( 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>" ;
}
}
]
} ) ; Etapa 1: Crie DTO, Etapa 2: Adicione DTO ao pai DTO Etapa 3.Map no perfil de mapeamento Etapa 4: Adicione ao controlador (._appdbContext.customers.include (c => c.membershiptype) .tolist () ..) Etapa 5: Adicione para exibir a coluna como:
{
data : "membershipType.name"
} , Atribua a tabela à variável e use -a no método Remover:
< 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 a lógica vem incorporada (consulte Commit para arquivos e detalhes)
Adicione o atributo [Authorize] às ações do controlador ou no topo do controlador para restringir todas as ações
FilterConfig.cs:
filters . Add ( new AuthorizeAttribute ( ) ) ;Isso desativa todos os controladores para usuários não autorizados, mas você pode adicionar [allowanonymous] a controladores ou ações para ativar o acesso
Semear o banco de dados : para manter a consistência do projeto em diferentes cenários de trabalho, adicione -os a uma migração
Crie visualizações separadas para convidados e usuários autorizados
no controlador:
public ViewResult Index ( int ? pageIndex , string sortBy )
{
if ( User . IsInRole ( RoleName . CanManageMovies ) )
return View ( "List" ) ;
return View ( "ReadOnlyList" ) ;
} Para desativar outras ações, acessar adicione este atributo: [Authorize(Roles = RoleName.CanManageMovies)]
Crie um modelo para manter as funções Rolename.cs:
public const string CanManageMovies = "CanManageMovies" ; Para adicionar campos personalizados ao usuário: adicione o suporte à classe de usuário do aplicativo e à ViewModel da visualização. Adicione também um novo suporte para registrar a seção de atribuição de ações
Ativar SSL nas propriedades, adicione filtro
filters . Add ( new RequireHttpsAttribute ( ) ) ;Obtenha Appid e AppSecret do Facebook, Google ... Insira no startup.auth.cs
app . UseFacebookAuthentication (
appId : "id" ,
appSecret : "secret" ) ;Adicione quaisquer adereços personalizados ao formulário de login externo e ao ViewModel. Inicialize no controlador de login externo

Em Nuget, instale vislumbrar.mvc5 e vislumbrar.ef6, vá para /glimse.axd e habilite
Desativar o cache: [OutputCache(Duration = 0, VaryByParam = "*", NoStore = true)]
Ativar cache:
[OutputCache(Duration=50,Location=OutputCacheLocation.Server,VaryByParam="genre")]
na ação do controlador
if ( MemoryCache . Default [ "Genres" ] == null )
{
MemoryCache . Default [ "Genres" ] = _appDbContext . Genres . ToList ( ) ;
}
var genres = MemoryCache . Default [ "Genres" ] as IEnumerable < Genre > ; em web.config em system.web
Vamos adicionar um recurso de aluguel ao nosso aplicativo Criar DTO: Newrentaldto:
public class NewRentalDto
{
public int CustomerId { get ; set ; }
public List < int > MovieIds { get ; set ; }
}Criar modelo: aluguel, adicione ao contexto e execute uma migração
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 ; }
}Mais detalhes sobre compromissos. (Usado Typeahead, Bloodhound para preenchimento automático)
Clique com o botão direito e publicar
PM> update-database -script -SourceMigration:SeedUsers
alvo mig para durar. Você tem uma consulta SQL do seu banco de dados agora
Em web.config <appSettings key="value"></appSettings> ou crie externamente outro arquivo de configuração <appSettings configSource="AppSettings.config"></appSettings> Use em código como: ConfigurationManager.AppSettings["Key"] Nothe: AppeTtings sempre retorna. você precisa convertê -lo para suas necessidades manualmente
em web.config Adicionar a <system.web>
<customErrors mode="On"></customErrors>
ON: Habilitar em todos os lugares remotos: desativar na localhost
Personalize em visualizações> Error compartilhado.cshtml
em web.config Adicionar a <system.web> <customErrors>
< system .web>
< customErrors mode = " On " >
< error statusCode = " 404 " redirect = " ~/404.html " />
</ customErrors >
<!-- ..... -->
</ system .web> n web.config add to <system.webServer>
< httpErrors errorMode = " Custom " >
< remove statusCode = " 404 " />
< error statusCode = " 404 " path = " 404.html " responseMode = " File " />
</ httpErrors >Custom: Ativar em todos os lugares detalhados: desativar na localhost
NUGET> Elmah
Exceção Logger. Acesso por /elmah.axd
Por padrão, ele salva logs na memória, mas com uma pequena configuração, poderíamos ter essas exceções em todos os tipos de bancos de dados
Para acessar remotamente, adicione isso a Elmah
< authorization >
< allow roles = " admin,user2,user3,... " />
< deny users = " * " />
</ authorization >OBRIGADO!!!