ASP.NET Core快速入门教程

目录
  • 第一课 基本概念
  • 第二课 控制器的介绍
  • 第三课 视图与表单
  • 第四课 数据验证
  • 第五课 路由规则
  • 第六课 应用发布与部署
  • 源码地址

第一课 基本概念

  • 基本概念

    • Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架

      • 符合Web应用特点
      • .NET Core跨平台解决方案
      • MVC设计模式的一种实现
  • 环境准备

第二课 控制器的介绍

  • 控制器定义方式:

    • 命名以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
    /// <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方法配置路由模板
    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文件
        • 配置MvcRazorCompileOnPublishfalse
<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>
<!-- 依赖框架的部署 (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快速入门教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Visual Studio ASP.NET Core MVC入门教程第一篇

    ASP.NET Core MVC入门教程第一节课,具体内容如下 1.开始环境 visual studio 2017 社区版或其他版本.安装时勾选"Web和云"组中的"ASP.NET及网页开发"项和"其他工具"组中的".NET Core平台开发"项. 2.创建一个网页应用 (1)在 Visual Studio中, select 文件 >新建 >项目. (2) 在"新项目"对话框中的左面板中,点击&

  • 快速入门ASP.NET Core看这篇就够了

    本来这篇只是想简单介绍下ASP.NET Core MVC项目的(毕竟要照顾到很多新手朋友),但是转念一想不如来点猛的(考虑到急性子的朋友),让你通过本文的学习就能快速的入门ASP.NET Core.既然是快速入门所以过多过深的内容我这里就一笔带过了!然后在后面的一些列文章中再慢慢的对其中的概念进行阐述. .NET Core是什么 很多朋友看到.NET Core就认为是ASP.NET Core,其实这是有误区的,因为.NET Core 是开放源代码的通用开发平台 (是一个"平台"),基于

  • ASP.NET Core快速入门之环境篇

    前言 ASP.NET Core 是一个开源和跨平台的框架,用于构建如 Web 应用.物联网(IoT)应用和移动后端应用等连接到互联网的基于云的现代应用程序.ASP.NET Core 应用可运行于 .NET Core 和完整的 .NET Framework 之上.它整合了原来ASP.NET中的MVC和WebApi框架,你可以在 Windows.Mac 和 Linux 上跨平台的开发和运行你的 ASP.NET Core 应用. vmware虚拟机安装 vmware哪里下载?360软件管家就可以下载.

  • ASP.NET Core快速入门之实战篇

    NO1 留言板(mysql的使用) 演示:http://haojima.net 这个功能很简单.就是对数据库的写入和展示.如果在Windows下,相信大家分分钟都可以搞定.而初次接触.net core + mysql可能需要注意些细节. 首先打开vs2017新建一个asp.net core项目(选Web应用程序),然后nuget 导入Microsoft.EntityFrameworkCore.Tools 1.1.1和MySql.Data.EntityFrameworkCore 8.0.8-dmr

  • ASP.NET Core快速入门教程

    目录 第一课 基本概念 第二课 控制器的介绍 第三课 视图与表单 第四课 数据验证 第五课 路由规则 第六课 应用发布与部署 源码地址 第一课 基本概念 基本概念 Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架 符合Web应用特点 .NET Core跨平台解决方案 MVC设计模式的一种实现 环境准备 安装最新版Visual Studio 2017 安装最新版.NET Core Sdk 第二课 控制器的介绍 控制器定义方式: 命名以Controller结尾 使用

  • jQuery Easyui快速入门教程

    1.什么是JQuery EasyUI jQuery EasyUI是一组基于JQuery的UI插件集合,而JQueryEasyUI的目标就是帮助开发者更轻松的打造出功能丰富并且美观的UI界面.开发者不需要编写复杂的JavaScript,也不需要对css样式有深入的了解,开发者需要了解的只是一些简单的html标签. 2.学习jQuery EasyUI的条件 因为JQueryEasyUI是基于jQuery的UI库,所以,必须需要JQuery课程的基础. 3.JQuery EasyUI的特点 基于JQu

  • OpenStack云计算快速入门教程(1)之OpenStack及其构成简介

    该教程基于Ubuntu12.04版,它将帮助读者建立起一份OpenStack最小化安装.我是五岳之巅,翻译中多采用意译法,所以个别词与原版有出入,请大家谅解.我不是英语专业,我觉着搞技术最重要的就是理解,而不是四级和考研中那烦人的英译汉,所以我的目标是忠于原意.通俗表达,Over.英文原文在这里(http://docs.openstack.org/es@***/openstack-compute/starter/content/ ,请将ex@***中的@去掉,CU屏蔽的F词),下面步入正题: 第

  • ReactJs快速入门教程(精华版)

    现在最热门的前端框架有AngularJS.React.Bootstrap等.自从接触了ReactJS,ReactJs的虚拟DOM(Virtual DOM)和组件化的开发深深的吸引了我,下面来跟我一起领略ReactJs的风采吧~~ 文章有点长,耐心读完,你会有很大收获哦~   一.ReactJS简介 React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设 Instagram 的网站.做出来以后,发现这套东西

  • Yii2框架制作RESTful风格的API快速入门教程

    先给大家说下什么是REST restful REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. 它首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是HTTP规范的主要编写者之一. 他在论文中提到:"我这篇文章的写作目的,就是想在符合架构原理的前提下,理解和评估以网络为基础的应用软件的架构设计,得到一个功能强.性能好.适宜通信的架构.REST指的是一组架构约束条件和原则." 如

  • Vue.js快速入门教程

    像AngularJS这种前端框架可以让我们非常方便地开发出强大的单页应用,然而有时候Angular这种大型框架对于我们的项目来说过于庞大,很多功能不一定会用到.这时候我们就需要评估一下使用它的必要性了.如果我们仅仅需要在一个简单的网页里添加屈指可数的几个功能,那么用Angular就太麻烦了,必要的安装.配置.编写路由和设计控制器等等工作显得过于繁琐. 这时候我们需要一个更加轻量级的解决方案.Vue.js就是一个不错的选择.Vue.js是一个专注于视图模型(ViewModal)的框架.视图模型是U

  • Vue.js 60分钟快速入门教程

    vuejs是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的.相比于Angular.js,Vue.js提供了更加简洁.更易于理解的API,使得我们能够快速地上手并使用Vue.js. 如果你之前已经习惯了用jQuery操作DOM,学习Vue.js时请先抛开手动操作DOM的思维,因为Vue.js是数据驱动的,你无需手动操作DOM.它通过一些特殊的HTML语法,将DOM和数据绑定起来.一旦你创建了绑定,DOM将和数据保持同步,每当变更了数据,DOM也会相应地更新. 当

随机推荐