第一课 基本概念
- 基本概念
- asp.net core mvc是.net core平台下的一种web应用开发框架
- 符合web应用特点
- .net core跨平台解决方案
- mvc设计模式的一种实现
- asp.net core mvc是.net core平台下的一种web应用开发框架
- 环境准备
- 安装最新版visual studio 2017
- 安装最新版.net core sdk
第二课 控制器的介绍
- 控制器定义方式:
- 命名以
controller
结尾 - 使用
controllerattribute
标注
- 命名以
public class testcontroller : controller { } [controller] public class test : controller { }
默认路由规则
- 域名/控制器类/方法
{domain}/{controller}/{action}
数据形式
querystring
: ?name=zhangsan&age=22form
cookie
session
header
httprequest
- httprequest 是用户请求对象
- 提供获取请求数据的属性
- cookies,headers,query,querystring,form
public iactionresult hello() { // query var name = request.query["name"]; // querystring var query = request.querystring.value; // form var username = request.form["username"]; // cookies var cookie = request.cookies["item"]; // headers var headers = request.headers["salt"]; return content("hello"); }
- httpcontext
- httpcontext是用户请求上下文
- 提供session属性获取session对象
- session.set 设置
- session.remove 移除
- session.trygetvalue 获取数据
public iactionresult hello() { // byte[] httpcontext.session.set("byte", new byte[] { 1, 2, 3, 4, 5 }); var bytes = httpcontext.session.get("byte"); // string httpcontext.session.setstring("name", "tom"); var name = httpcontext.session.getstring("name"); // int httpcontext.session.setint32("id", 20); var id = httpcontext.session.getint32("id"); httpcontext.session.remove("name"); httpcontext.session.clear(); return content("hello"); }
- 数据绑定
- 把用户请求的数据绑定到控制器方法的参数上
- 支持简单类型与自定义类型
- 绑定规则是请求数据名称与参数名称一致
- 如查询字符串key名称跟参数一致
- form表单名称跟参数一致
public iactionresult hello(requestmodel request,int? age) { // 查询字符串 var test = request.query["test"]; // 简单类型 var userage = age; // 自定义类型 var name = request.name; return content("hello"); } public class requestmodel { public string name { get; set; } }
- 内容补充
- 如果以controller结尾的都是控制器,那如果程序里面由一些业务命名的时候也是以controller结尾,怎么办?
noncontrollerattribute
/// <summary> /// 拍卖师控制类 /// </summary> [noncontroller] public class auctioncontroller { }
- 常用特性
特性 | 数据源 |
---|---|
fromheaderattribute | 请求头数据 |
fromrouteattribute | 路由数据 |
frombodyattribute | 请求体 |
fromformattribute | 表单数据 |
fromqueryattribute | 查询字符串 |
fromservicesattribute | 服务注册 |
public iactionresult say( [fromform]string name, [fromquery]int age, [fromheader] string salt, [frombody] string content ) { return view(); }
特性参数
- 通过特性修饰参数来影响绑定逻辑
- 灵活扩展
iactionresult
- 动作结果接口
- 具体实现
- jsonresult:返回json结构数据
- redirectresult:跳转到新地址
- fileresult:返回文件
- viewresult:返回视图内容
- contentresult:文本内容
第三课 视图与表单
- 数据传递
- viewdata
- viewbag
- tempdata
- model
- session
- cache
viewdata | viewbag |
---|---|
键值对 | 动态类型 |
索引器 | viewdata的封装 |
支持任意类型 | 动态属性 |
tempdata | cache | session |
---|---|---|
视图级别 | 应用程序级别 | 会话级别 |
只允许消费一次 | 服务器端保存 | 服务器端保存 |
可多次赋值 | 可设置有效期 | 键值对形式 |
键值对形式 | 键值对形式 |
- cache
- 与.net framework时代不同,一种全新实现
- imemorycache接口
- 依赖注入方式获取
- imemorycache.get/set操作数据
[controller] public class test : controller { private readonly imemorycache _cache; public test(imemorycache memorycache) { this._cache = memorycache; } public iactionresult readcache() { _cache.set("name","tom"); _cache.get("name"); _cache.set("age",30); _cache.get("age"); user tom = new user(){ name = "admin",pwd = "123456"}; _cache.set<user>("user",tom); _cache.get<user>("user"); return content("ok"); } } public class user { public string name { get; set; } public string pwd { get; set; } }
- viewstart
- 以_viewstart.cshtml命名,固定名称,不能更换
- 一般放在视图所在目录的根目录下
- 自动执行,无需手工调用
- 不要再viewstart中做大量的业务操作
- viewimport
- 以_viewimport.cshtml命名,固定名称,不能更换
- 只作引入操作
- 一般放在视图所在目录的根目录下
- 自动执行,无需手工调用
- 视图中可以使用@using关键字引入所需命名空间
- 通过viewimport做全局性的命名空间引入,减少在每个页面中引入的工作量
第四课 数据验证
- 数据验证特性
validationattribute
public abstract class validationattribute : attribute { /// <summary>initializes a new instance of the <see cref="t:system.componentmodel.dataannotations.validationattribute"></see> class.</summary> protected validationattribute(); /// <summary>initializes a new instance of the <see cref="t:system.componentmodel.dataannotations.validationattribute"></see> class by using the function that enables access to validation resources.</summary> /// <param name="errormessageaccessor">the function that enables access to validation resources.</param> /// <exception cref="t:system.argumentnullexception"><paramref name="errormessageaccessor">errormessageaccessor</paramref> is null.</exception> protected validationattribute(func<string> errormessageaccessor); /// <summary>initializes a new instance of the <see cref="t:system.componentmodel.dataannotations.validationattribute"></see> class by using the error message to associate with a validation control.</summary> /// <param name="errormessage">the error message to associate with a validation control.</param> protected validationattribute(string errormessage); /// <summary>gets or sets an error message to associate with a validation control if validation fails.</summary> /// <returns>the error message that is associated with the validation control.</returns> public string errormessage { get; set; } /// <summary>gets or sets the error message resource name to use in order to look up the <see cref="p:system.componentmodel.dataannotations.validationattribute.errormessageresourcetype"></see> property value if validation fails.</summary> /// <returns>the error message resource that is associated with a validation control.</returns> public string errormessageresourcename { get; set; } /// <summary>gets or sets the resource type to use for error-message lookup if validation fails.</summary> /// <returns>the type of error message that is associated with a validation control.</returns> public type errormessageresourcetype { get; set; } /// <summary>gets the localized validation error message.</summary> /// <returns>the localized validation error message.</returns> protected string errormessagestring { get; } /// <summary>gets a value that indicates whether the attribute requires validation context.</summary> /// <returns>true if the attribute requires validation context; otherwise, false.</returns> public virtual bool requiresvalidationcontext { get; } /// <summary>applies formatting to an error message, based on the data field where the error occurred.</summary> /// <param name="name">the name to include in the formatted message.</param> /// <returns>an instance of the formatted error message.</returns> public virtual string formaterrormessage(string name); /// <summary>checks whether the specified value is valid with respect to the current validation attribute.</summary> /// <param name="value">the value to validate.</param> /// <param name="validationcontext">the context information about the validation operation.</param> /// <returns>an instance of the <see cref="system.componentmodel.dataannotations.validationresult"></see> class.</returns> public validationresult getvalidationresult( object value, validationcontext validationcontext); /// <summary>determines whether the specified value of the object is valid.</summary> /// <param name="value">the value of the object to validate.</param> /// <returns>true if the specified value is valid; otherwise, false.</returns> public virtual bool isvalid(object value); /// <summary>validates the specified value with respect to the current validation attribute.</summary> /// <param name="value">the value to validate.</param> /// <param name="validationcontext">the context information about the validation operation.</param> /// <returns>an instance of the <see cref="system.componentmodel.dataannotations.validationresult"></see> class.</returns> protected virtual validationresult isvalid( object value, validationcontext validationcontext); /// <summary>validates the specified object.</summary> /// <param name="value">the object to validate.</param> /// <param name="validationcontext">the <see cref="t:system.componentmodel.dataannotations.validationcontext"></see> object that describes the context where the validation checks are performed. this parameter cannot be null.</param> /// <exception cref="t:system.componentmodel.dataannotations.validationexception">validation failed.</exception> public void validate(object value, validationcontext validationcontext); /// <summary>validates the specified object.</summary> /// <param name="value">the value of the object to validate.</param> /// <param name="name">the name to include in the error message.</param> /// <exception cref="t:system.componentmodel.dataannotations.validationexception"><paramref name="value">value</paramref> is not valid.</exception> public void validate(object value, string name); }
常用数据验证
- requiredattribute
- regularexpressionattribute
- compareattribute
- rangeattribute
- maxattribute
- minattribute
- stringlengthattribute
- datatypeattribute
服务器端使用
- 使用包含验证规则的类接收数据
- 使用modelstate.isvalid判断是否符合要求
前端使用
- 定义强类型视图并传递包含验证规则的业务数据模型
- 使用htmlhelper.validationfor初始前端验证规则
- 使用htmlhelper.validationmessagefor生成提示文字
public class userlogin { [required(errormessage = "用户名不能为空")] [stringlength(10,errormessage = "用户名长度不能超过10位")] public string username { get; set; } //[required(errormessage = "密码不能为空")] [stringlength(6,errormessage = "密码长度不能超过6位")] public string password { get; set; } }
public class formcontroller : controller { public iactionresult index() { return view(new userlogin()); } public iactionresult postdata(userlogin login) { return content(modelstate.isvalid?"数据有效":"数据无效"); } }
@model lesson2.models.userlogin @{ layout = null; } <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>index</title> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script> <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script> </head> <body> <form asp-action="postdata" method="post"> <table> <tr> <td>用户名</td> <td>@html.textboxfor(m => m.username)</td> <td>@html.validationmessagefor(m => m.username)</td> </tr> <tr> <td>密码</td> <td>@html.passwordfor(m => m.password)</td> <td>@html.validationmessagefor(m => m.password)</td> </tr> <tr> <td></td> <td><input type="submit" value="登录" /></td> <td></td> </tr> </table> </form> </body> </html>
第五课 路由规则
路由
- 定义用户请求与控制器方法之前的映射关系
路由配置
- iroutebuilder
- 通过maproute方法配置路由模板
- iroutebuilder
app.usemvc(routes => { routes.maproute( name: "default", template: "{controller=home}/{action=index}/{id?}"); routes.maproute( name: "admin_default", template: "admin/{controller=home}/{action=index}/{id?}"); });
- routeattribute
- 应用在控制器及方法上
- 通过template属性配置路由模板
[route("admin/form")] public class formcontroller : controller { [route("index")] public iactionresult index() { return view(new userlogin()); } public iactionresult postdata(userlogin login) { return content(modelstate.isvalid?"数据有效":"数据无效"); } }
- 路由约束
- 对路由数据进行约束
- 只有约束满足条件才能匹配成功
约束 | 示例 | 说明 |
---|---|---|
required | "product/{productname:required}" | 参数必选 |
alpha | "product/{productname:alpha}" | 匹配字母,大小写不限 |
int | "product/{productid:int}" | 匹配int类型 |
··· | ··· | ··· |
composite | "product/{productid:composite}" | 匹配composite类型 |
length | "product/{productname:length(5)}" | 长度必须是5个字符 |
length | "product/{productname:length(5)}" | 长度在5-10之间 |
maxlength | "product/{productid:maxlength(10)}" | 最大长度为10 |
minlength | "product/{productid:minlength(3)}" | 最小长度为3 |
min | "product/{productid:min(3)}" | 大于等于3 |
max | "product/{productid:max(10)}" | 小于等于10 |
range | "product/{productid:range(5,10)}" | 对应的数组在5-10之间 |
regex | "product/{productid:regex(^\d{4}$)}" | 符合指定的正则表达式 |
- 路由数据
- 路由数据也是请求数据的一部分
- 路由数据与表单数据一样,也可以绑定到参数上
- 默认是通过名称进行匹配,也可以通过
formrouteattribute
匹配参数与路由数据的映射关系
public iactionresult index([fromroute] int? id) { return view(); }
第六课 应用发布与部署
- 发布
- 发布方法
- 使用
visual studio
发布应用:项目右键 -> 发布 -> 发布方式选择...
- 使用
dotnet publish
命令行工具发布:dotnet publish --configuration release --runtime win7-x64 --output c:\svc
- 使用
- 发布方法
- 视图预编译
- 少了运行时编译过程,启动速度快
- 预编译后,整个程序包更小
- 可以通过mvcrazorcompileonpublish配置是否开启,默认是开启状态
- 关闭视图预编译:
- 打开项目的
.csproj
文件 - 配置
mvcrazorcompileonpublish
为false
- 打开项目的
- 关闭视图预编译:
<project sdk="microsoft.net.sdk.web"> <propertygroup> <targetframework>netcoreapp2.1</targetframework> <!-- 关闭视图预编译 --> <mvcrazorcompileonpublish>false</mvcrazorcompileonpublish> </propertygroup> <itemgroup> <packagereference include="microsoft.aspnetcore.app" /> <packagereference include="microsoft.aspnetcore.razor.design" version="2.1.2" privateassets="all" /> <packagereference include="microsoft.visualstudio.web.codegeneration.design" version="2.1.1" /> </itemgroup> </project>
- 部署
- iis 部署
- 目标机器安装对应版本的.net core sdk
- 安装.net core windows server 托管程序
- 应用程序池的“.net clr版本”设置为“无托管代码”
- 自宿主发布
- 发布成一个exe直接运行
- 不用依赖iis
- runtimeidentifier
- .net core rid catalog
- iis 部署
<!-- 依赖框架的部署 (fdd) --> <propertygroup> <targetframework>netcoreapp2.2</targetframework> <runtimeidentifier>win7-x64</runtimeidentifier> <selfcontained>false</selfcontained> <istransformwebconfigdisabled>true</istransformwebconfigdisabled> </propertygroup> <!-- 独立部署 (scd) --> <propertygroup> <targetframework>netcoreapp2.2</targetframework> <runtimeidentifier>win7-x64</runtimeidentifier> <istransformwebconfigdisabled>true</istransformwebconfigdisabled> </propertygroup> ... ... ...
源码地址
到此这篇关于asp.net core快速入门教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持代码网。
发表评论