☀AspNetCore 学习笔记(Mvc 篇),学生管理系统
相关项目:Asp.Net Core学习 WebApi版 图书馆管理系统
新项目推荐:使用 AspNetCore 开发博客
| 公众号 | 公众号 |
|---|---|
Asp.Net Core 学习笔记系列博客:
C#语言学习系列博客:
相关博文推荐:
像Django那样自动检查代码更新,自动重载服务器(太方便了)
dotnet watch run设置项目文件的AspNetCoreHostingModel属性。
netcoreapp2.2
InProcess
通过在Configure中添加参数ILogger logger引入Asp.Net Core自带的日志组件。
…输出日志:(可以看到三个中间件的执行过程)
…所有静态文件都在目录wwwroot下
// 设置默认文件
// 不设置的话,默认就是index.html/default.html这几个
var defaultFileOpinions = new DefaultFilesOptions();
defaultFileOpinions.DefaultFileNames.Clear();
defaultFileOpinions.DefaultFileNames.Add("test.html");
// 添加默认文件中间件,必须在UseStaticFiles之前注册
app.UseDefaultFiles(defaultFileOpinions);
// 添加静态文件中间件
app.UseStaticFiles();可以在浏览器浏览 wwwroot 下的内容。不推荐在生产环境中使用。
app.UseDirectoryBrowser();集成了UseDefaultFiles, UseStaticFiles, UseDirectoryBrowser三个中间件的功能。同样不推荐在生产环境中使用。
var fileServerOpinions = new FileServerOptions();
fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Clear();
fileServerOpinions.DefaultFilesOptions.DefaultFileNames.Add("test.html");
app.UseFileServer(fileServerOpinions);if (env.IsDevelopment())
{
var developerExceptionPageOptions = new DeveloperExceptionPageOptions();
// 显示代码行数
developerExceptionPageOptions.SourceCodeLineCount = 10;
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
throw new Exception("自己抛出的异常");
});Ops:
ASPNETCORE_ENVIRONMENT环境变量设置开发环境。launchSettings.json文件中设置环境变量。IHostEnvironment服务访问运行时环境public void ConfigureServices(IServiceCollection services)
{
// 单纯引入核心MVC服务,只有核心功能
services.AddMvcCore();
// 一般用这个,功能多
services.AddMvc();
}public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger)
{
if (env.IsDevelopment())
{
var developerExceptionPageOptions = new DeveloperExceptionPageOptions();
// 显示代码行数
developerExceptionPageOptions.SourceCodeLineCount = 10;
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}MVC路由规则:/控制器名称/方法名称,(不区分大小写)
例如下面例子的路由是:/home/index
public class HomeController : Controller
{
public string Index()
{
return "home controller";
}
}public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string ClassName { get; set; }
public string Email { get; set; }
}public interface IStudentRepository
{
Student GetById(int id);
void Save(Student student);
}目前还没接入数据库,定义一个假数据的类
…Asp.Net Core依赖注入容器注册服务有三种
依赖注入的优点
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// 注册依赖注入,将实现类与接口绑定
services.AddSingleton();
}public class StudentController : Controller
{
private readonly IStudentRepository _studentRepository;
// 通过构造函数注入的方式注入 IStudentRepository
public StudentController(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public JsonResult Index(int id)
{
return Json(_studentRepository.GetById(id));
}
}在控制器方法中使用 ObjectResult 返回类型,支持内容协商,根据请求头参数返回数据,
// 支持内容格式协商
public ObjectResult Details(int id)
{
return new ObjectResult(_studentRepository.GetById(id));
}如:
Accept: application/xml将返回xml格式。注:还要添加xml序列化器。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
// 注册XML序列化器
.AddXmlSerializerFormatters();
}前两种都是弱类型的
使用方法:
ViewData["Title"] = "学生视图";
ViewData["Model"] = model;cshtml代码:
@ViewData["Title"]
@{
var student = ViewData["model"] as StudyManagement.Models.Student;
}
// 直接给动态属性赋值
ViewBag.PageTitle = "ViewBag标题";
ViewBag.Student = model;cshtml使用:
@ViewBag.PageTitle
在控制器中传给View()模型
public IActionResult GetView()
{
var model = _studentRepository.GetById(1);
return View(model);
}在cshtml中指定模型类型
@model StudyManagement.Models.Student
强类型模型
@Model.Id
@Model.Name
@Model.ClassName
@Model.Email
类似于DTO(数据传输对象)
public class StudentDetailsViewModel
{
public Student Student { get; set; }
public string PageTitle { get; set; }
}public IActionResult Details()
{
var model = _studentRepository.GetById(1);
var viewModel = new StudentDetailsViewModel
{
Student = model,
PageTitle = "viewmodel里的页面标题"
};
return View(viewModel);
}
@model StudyManagement.ViewModels.StudentDetailsViewModel
强类型模型
@Model.PageTitle
@Model.Student.Id
@Model.Student.Name
@Model.Student.ClassName
@Model.Student.Email
@model IEnumerable
Id
姓名
班级
邮箱
@foreach (var student in Model)
{
@student.Id
@student.Name
@student.ClassName
@student.Email
}
@ViewBag.Title
@RenderSection("Scripts", required: false)
@model IEnumerable
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "首页 学生列表";
}
在布局视图里渲染节点
@RenderSection("Scripts", required: false)在普通视图里定义节点
@section Scripts{
}我的理解就是_ViewStart.cshtml文件所在目录下的每个视图文件开始渲染先执行这个文件的内容。一般直接放在Views目录下,全局生效,可以放在各个子文件夹下,这样可以覆盖全局的_ViewStart.cshtml。
@{
Layout = "_Layout";
}用来导入命名空间、注册模型等等n多种操作。
生效机制和ViewStart差不多。
在MapRoute方法中传入就好了。
// 自定义路由
app.UseMvc(route =>route.MapRoute("default",
"{controller=Home}/{action=Index}/{id?}"));比传统路由更加灵活,可以搭配传统路由使用。
即在控制器方法上添加路由注解,一个方法可以同时映射多个路由。
[Route("Home/Index")]
public IActionResult Index()
{
return View(_studentRepository.GetAll());
}路由中也可以指定参数
[Route("test/{id?}")]
public IActionResult Details(int id = 1)
{
var model = _studentRepository.GetById(id);
var viewModel = new StudentDetailsViewModel
{
Student = model,
PageTitle = "viewmodel里的页面标题"
};
return View(viewModel);
}可以直接在控制器类上加注解,[controller]/[action]。
优点:根据参数自动生成,不需要手写超链接,类似Django模板里面的url命令。
在ViewImport中添加TagHelper
@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers比如,链接TagHelper使用
查看
缓存破坏的TagHelper
在开发环境中使用本地css文件,在非开发环境下使用的是CDN的css文件。
注:integrity是用来做完整性检查的,保证CDN提供文件的完整和安全。
为了防止CDN加载失败页面无法显示,可以加上fallback相关属性,第一个是失败时加载的文件,第二个是不检查这个文件的完整性
asp-fallback-href="~/lib/twitter-bootstrap/css/bootstrap.css"
asp-suppress-fallback-integrity="true"直接贴上一个布局的代码,把class样式都去掉了,保留最基本代码。
确实是很方便的,和Django、jinja2之类的模板比完全不输。
@model Student
()">
提交
将Http请求中的数据绑定到控制器方法上对应参数的顺序:
首先在Model中加入验证属性,如:
public class Student
{
public int Id { get; set; }
[Display(Name = "姓名"), MaxLength(4, ErrorMessage = "名字长度不能超过四个字")]
[Required(ErrorMessage = "请输入名字!")]
public string Name { get; set; }
[Display(Name = "班级")]
public ClassNameEnum ClassName { get; set; }
[Required(ErrorMessage = "请输入邮箱!")]
[Display(Name = "邮箱")]
[RegularExpression(@"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$", ErrorMessage = "邮箱格式不正确")]
public string Email { get; set; }
}使用ModelState.IsValid来验证模型属性是否正确
[HttpPost]
public IActionResult Create(Student student)
{
if (ModelState.IsValid)
{
var newStudent = _studentRepository.Add(student);
return RedirectToAction("details", new { id = newStudent.Id });
}
return View();
}例子如下:
public class AppDbContext:DbContext
{
// 将应用程序的配置传递给DbContext
public AppDbContext(DbContextOptions options) : base(options) { }
// 对要使用到的每个实体都添加 DbSet 属性
// 通过DbSet属性来进行增删改查操作
// 对DbSet采用Linq查询的时候,EFCore自动将其转换为SQL语句
public DbSet Students { get; set; }
}services.AddDbContextPool(options => options.UseSqlServer(_configuration.GetConnectionString("StudentDBConnection")));其中,本地SqlServer数据库的配置,在appserttings.json中:
"ConnectionStrings": {
"StudentDBConnection": "server=(localdb)\\MSSQLLocalDB;database=StudentDB;Trusted_Connection=true"
}…在nuget控制台中,不区分大小写
about_enti全名很长可以只写前面的使用dotnet cli的话请先安装:dotnet tool install --global dotnet-ef
重写DbContext的OnModelCreating方法
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity().HasData(
new Student { Id = 1, Name = "小米" },
);
}为了避免DbContext代码太乱,也可以使用扩展方法的方式:
public static class ModelBuilderExtensions
{
public static void InsertSeedData(this ModelBuilder mBuilder)
{
mBuilder.Entity().HasData(暂无开放 Issues,或尚未同步最近议题。