这是一个使用.NET Framework 4.8开发的MVC应用程序。
动作结果
| 类型 | 辅助方法 |
|---|---|
| ViewResult | 看法() |
| partialViewResult | partialview() |
| contentResult | 内容() |
| 重定向 | redirect() |
| redirecttorouteresult | redirecttoaction() |
| jsonresult | json() |
| filesult | 文件() |
| httpnotfoundresult | httpnotfound() |
| 空的 | - |
一些例子
public ActionResult Test ( )
{
return View ( data ) ;
return Content ( "Hello World!" ) ;
return HttpNotFound ( ) ;
return new EmptyResult ( ) ;
return RedirectToAction ( "Index" , "Home" , new { page = "1" , sortBy = "name" } ) ;
} 基于约定的路由:在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属性路由:在Routeconfig.cs中添加routes.MapMvcAttributeRoutes();控制器使用属性[Route("url template")] 。还可以使用诸如Min,Max,最小值,最大长度,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 >在视图中创建视图,然后选择部分视图。在另一个视图中使用@Html.Partial("_PartialView", Model.Data)




实体框架:通过使用上下文文件将关系数据库中数据映射到我们对象的ORM。
LINQ:像SQL查询一样的方法。
工作流程:数据库首先,代码。
DB首先:首先设计数据库表,后来让EF根据表生成域类。
代码首先:首先创建域类,然后让EF为我们生成数据库表。
dbset到上下文中的表名:dbcontext类中的dbcontext类中的package manager console PM > enable-migrations , PM> add-migration migrationName , PM> update-database
播种DB:将SQL命令放在迁移up()方法中
在控制器中
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 ) ;
} 负载关系外来表: _context.Customer.Include(c=>c.MembershipType).ToList();





从视图中:
@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 >
} 在具有数据注释的模型中:
[ Display ( Name = "Date of Birth" ) ]
public DateTime ? Birthdate { get ; set ; }或使用<label for="Birthdate">Date of Birth</label>
创建ViewModel:
public class NewCustomerViewModel
{
public IEnumerable < MembershipType > MembershipTypes { get ; set ; }
public Customer Customer { get ; set ; }
}在控制器中:
var membershipTypes = _context . MembershipTypes . ToList ( ) ;
var viewModel = new NewCustomerViewModel ( )
{
MembershipTypes = membershipTypes
} ;从视图中:
< 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 > 在控制器中:
[ HttpPost ]
public ActionResult Create ( Customer customer )
{
//...
return View ( ) ;
}考虑到操作名称和控制器名称
( Html . BeginForm ( actionName : "Create" , controllerName : "Customers" ) )
//... [ HttpPost ]
public ActionResult Create ( Customer customer )
{
_context . Customers . Add ( customer ) ;
_context . SaveChanges ( ) ;
return RedirectToAction ( "Index" , "Customers" ) ;
} 填写来自控制器中ID的相应项目的数据:
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 ) ;
}
} 如果不存在,则添加了更新。在控制器地图中属性
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" ) ;
}将因ID字段添加为隐藏:
@Html.HiddenFor(m= > m.Customer.Id)


步骤1:在模型中添加注释,步骤2:在控制器中添加验证控件。当用户数据没有有效的返回表格时
if ( ! ModelState . IsValid )
{
var viewModel = new CustomerFormViewModel
{
Customer = customer ,
MembershipTypes = _context . MembershipTypes . ToList ( )
} ;
return View ( "CustomerForm" , viewModel ) ;
}步骤3:将验证消息添加到视图:
@Html.ValidationMessageFor(m= > m.Customer.Name)样式验证错误访问这些类并进行样式化:
. field-validation-error {
color : red;
}
. input-validation-error {
border : 2 px red;
}模型中的覆盖验证消息将其添加到必需的数据注释
[ Required ( ErrorMessage = "Please enter customer's name." ) ]
[ StringLength ( 255 ) ]
public string Name { get ; set ; } 步骤1:创建一个继承验证的类(使用system.componentmodel.dataannotations)
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." )
}
}步骤2:将数据注释添加到模型
[ Display ( Name = "Membership Type" ) ]
[ Min18YearsIfAMember ]
public byte MembershipTypeId { get ; set ; }步骤3:添加消息以查看
@Html.ValidationMessageFor(m= > m.Customer.MembershipTypeId)@Html.ValidationSummary(true, "Please fix the following errors.")排除propertyerrors:true隐藏单个错误列表消息:显示给用户的消息(可以进行程式化)
将此添加到视图中的表单
@section scripts {
@Scripts . Render ( "~/bundles/jqueryval" )
} 在视图中使用此HTML助手:
@Html . AntiForgeryToken ( )并在控制器操作中添加此数据注释:
在控制器中创建Web API和将其添加到global.asax.js:
GlobalConfiguration . Configure ( WebApiConfig . Register ) ;在控制器初始化上下文中:
private Context _context ;
public CustomersController ( )
{
_context = new Context ( ) ;
}创建get/post/put方法,例如:获取:
//GET /api/customers
[ HttpGet ]
public IEnumerable < Customer > GetCustomers ( )
{
return _context . Customers . ToList ( ) ;
}得到一个:
//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 ;
}创造:
//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 ;
}更新:
//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 ( ) ;
}删除:
//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 ( ) ;
}与Postman进行测试
我们删除不想更改或显示的数据的域对象。满足我们的需求。存储在DTOS文件夹中
在app_start中创建mappingprofile.cs:
public class MappingProfile : Profile
{
public MappingProfile ( )
{
Mapper . CreateMap < Customer , CustomerDto > ( ) ;
Mapper . CreateMap < CustomerDto , Customer > ( ) ;
}
}将映射器添加到global.asax.cs
protected void Application_Start ( )
{
Mapper . Initialize ( c => c . AddProfile < MappingProfile > ( ) ) ;
//..
}更新控制器操作:
//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 ( ) ;
} 在app_start webapiconfig.cs中添加寄存器
var settings = config . Formatters . JsonFormatter . SerializerSettings ;
settings . ContractResolver = new CamelCasePropertyNamesContractResolver ( ) ;
settings . Formatting = Formatting . Indented ; 正确的HTTP结果为我们的行为:
//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 ) ;
} 邮递员:获取:https:// localhost:44362/api/电影200
[
{
"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
},
//.......
]获取:https:// localhost:44362/api/movers/7 200
{
"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
}帖子:https:// localhost:44362/api/电影201创建
{
"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/movers/11 204没有内容
{
"name" : " Life Is Beautiful " ,
"genreId" : 3 ,
"dateAdded" : " 1900-01-01T00:00:00 " ,
"releaseDate" : " 1997-01-01T00:00:00 " ,
"numberInStock" : 5
}删除:https:// localhost:44362/api/movers/12 204无内容
在视图中,将类,数据和ID添加到项目中。最后脚本:
< 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 >
} 加入Bundleconfig.cs:
bundles . Add ( new ScriptBundle ( "~/bundles/bootstrap" ) . Include (
"~/Scripts/bootstrap.js" ,
"~/Scripts/bootbox.js" , //<--- here
"~/Scripts/respond.js"
) ) ;在视图中实施:
@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 >
}添加到捆绑包:(我们将第三方捆绑包合并到lib。in _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" ) ) ;在视图表中应具有ID和THEAD,TBODY标签。最后在脚本部分中,当文档准备就绪时:
$ ( document ) . ready ( function ( ) {
$ ( "#customers" ) . DataTable ( ) ;
//...
} 在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>" ;
}
}
]
} ) ; 步骤1:创建DTO,步骤2:将DTO添加到父dto步骤3.映射配置文件中的映射步骤4:添加到控制器(.__pdbcontext.customers.include(c => c.membershiptype).tolist(C => c.membershiptype).tolist().tolist()..
{
data : "membershipType.name"
} , 将表分配给变量并在删除方法中使用:
< 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 > 
所有逻辑都内置(请参阅文件和详细信息提交)
将[授权]属性添加到控制器操作或控制器的顶部以限制所有操作
FilterConfig.cs:
filters . Add ( new AuthorizeAttribute ( ) ) ;这可以禁用未经授权的用户的所有控制器
播种数据库:保持项目在不同的工作方案上的一致性添加到迁移中
为客人和授权用户创建单独的视图
在控制器中:
public ViewResult Index ( int ? pageIndex , string sortBy )
{
if ( User . IsInRole ( RoleName . CanManageMovies ) )
return View ( "List" ) ;
return View ( "ReadOnlyList" ) ;
}禁用其他操作访问访问添加此属性: [Authorize(Roles = RoleName.CanManageMovies)]
创建一个模型来保持角色rolename.cs:
public const string CanManageMovies = "CanManageMovies" ; 要将自定义字段添加到用户:将Prop添加到视图的应用程序用户类和ViewModel中。还添加新的道具以注册诉讼分配部分
在属性中启用SSL,添加过滤器
filters . Add ( new RequireHttpsAttribute ( ) ) ;从Facebook,Google ...插入startup.auth.cs中获取appid和appsecret
app . UseFacebookAuthentication (
appId : "id" ,
appSecret : "secret" ) ;将任何自定义道具添加到外部登录表单和ViewModel中。在外部登录控制器中初始化

在nuget install install install limpse.mvc5和limpse.ef6转到 /glimse.axd并启用
禁用缓存: [OutputCache(Duration = 0, VaryByParam = "*", NoStore = true)]
启用缓存:
[OutputCache(Duration=50,Location=OutputCacheLocation.Server,VaryByParam="genre")]
在控制器动作中
if ( MemoryCache . Default [ "Genres" ] == null )
{
MemoryCache . Default [ "Genres" ] = _appDbContext . Genres . ToList ( ) ;
}
var genres = MemoryCache . Default [ "Genres" ] as IEnumerable < Genre > ; 在system.web中的web.config中
我们将在我们的应用程序create dto:newrentaldto中添加租赁功能:
public class NewRentalDto
{
public int CustomerId { get ; set ; }
public List < int > MovieIds { get ; set ; }
}创建模型:租赁,添加到上下文并运行迁移
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 ; }
}有关提交的更多详细信息。 (使用打字,猎犬以自动完成)
右键单击并发布
PM> update-database -script -SourceMigration:SeedUsers
目标mig持续。您现在有SQL查询DB
在web.config <appSettings key="value"></appSettings>或外部创建另一个配置文件<appSettings configSource="AppSettings.config"></appSettings>在代码中使用: ConfigurationManager.AppSettings["Key"]注: appsettings始终返回strings strings。您需要手动转换它
在web.config中添加到<system.web>
<customErrors mode="On"></customErrors>
ON:启用无处不在的遥控器:禁用Localhost
在视图中自定义>共享错误。cshtml
在web.config中添加到<system.web> <customErrors>
< system .web>
< customErrors mode = " On " >
< error statusCode = " 404 " redirect = " ~/404.html " />
</ customErrors >
<!-- ..... -->
</ system .web>n web.config添加到<system.webServer>
< httpErrors errorMode = " Custom " >
< remove statusCode = " 404 " />
< error statusCode = " 404 " path = " 404.html " responseMode = " File " />
</ httpErrors >自定义:启用详细信息启用:在Localhost上禁用
Nuget> Elmah
异常记录器。 /elmah.axd访问
默认情况下,它将日志保存到内存,但是使用小配置,我们可以在各种数据库上有这些例外
用于访问远程将其添加到Elmah
< authorization >
< allow roles = " admin,user2,user3,... " />
< deny users = " * " />
</ authorization >谢谢!!!