您现在的位置是:网站首页> 编程资料编程资料
ASP.NET CORE基础教程_基础应用_
2023-05-24
375人已围观
简介 ASP.NET CORE基础教程_基础应用_
第一课 基本概念
- 基本概念
- 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=22
- Form
- 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
////// 拍卖师控制类 /// [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",tom); _cache.Get("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 { /// Initializes a new instance of the class. protected ValidationAttribute(); /// Initializes a new instance of the class by using the function that enables access to validation resources. /// The function that enables access to validation resources. /// errorMessageAccessor is null. protected ValidationAttribute(Func errorMessageAccessor); /// Initializes a new instance of the class by using the error message to associate with a validation control. /// The error message to associate with a validation control. protected ValidationAttribute(string errorMessage); /// Gets or sets an error message to associate with a validation control if validation fails. /// The error message that is associated with the validation control. public string ErrorMessage { get; set; } /// Gets or sets the error message resource name to use in order to look up the property value if validation fails. /// The error message resource that is associated with a validation control. public string ErrorMessageResourceName { get; set; } /// Gets or sets the resource type to use for error-message lookup if validation fails. /// The type of error message that is associated with a validation control. public Type ErrorMessageResourceType { get; set; } /// Gets the localized validation error message. /// The localized validation error message. protected string ErrorMessageString { get; } /// Gets a value that indicates whether the attribute requires validation context. /// true if the attribute requires validation context; otherwise, false. public virtual bool RequiresValidationContext { get; } /// Applies formatting to an error message, based on the data field where the error occurred. /// The name to include in the formatted message. /// An instance of the formatted error message. public virtual string FormatErrorMessage(string name); /// Checks whether the specified value is valid with respect to the current validation attribute. /// The value to validate. /// The context information about the validation operation. /// An instance of the class. public ValidationResult GetValidationResult( object value, ValidationContext validationContext); /// Determines whether the specified value of the object is valid. /// The value of the object to validate. /// true if the specified value is valid; otherwise, false. public virtual bool IsValid(object value); /// Validates the specified value with respect to the current validation attribute. /// The value to validate. /// The context information about the validation operation. /// An instance of the class. protected virtual Vali
相关内容
- .Net使用SuperSocket框架实现WebSocket前端_实用技巧_
- ASP.NET Core 3.0轻量级角色API控制授权库_实用技巧_
- .Net使用SuperSocket框架实现WebSocket后端_实用技巧_
- .Net Core部署Docker容器_基础应用_
- ASP.NET Core使用JWT自定义角色并实现策略授权需要的接口_实用技巧_
- .NET Core使用EF生成数据库出错的解决方法_实用技巧_
- .NET Core跨平台串口通讯使用SerialPortStream基础类库问题解决_实用技巧_
- .Net Core应用增强型跨平台串口类库CustomSerialPort()详解_实用技巧_
- .Net Core跨平台应用开发串口篇HelloArm_实用技巧_
- .NET Core、Xamarin、.NET Standard和.NET Framework四者之间的区别介绍_自学过程_
点击排行
本栏推荐
