广告
返回顶部
首页 > 资讯 > 后端开发 > ASP.NET >ASP.NET CORE基础教程
  • 404
分享到

ASP.NET CORE基础教程

2024-04-02 19:04:59 404人浏览 薄情痞子
摘要

目录第一课 基本概念第二课 控制器的介绍第三课 视图与表单第四课 数据验证第五课 路由规则第六课 应用发布与部署源码地址第一课 基本概念 基本概念ASP.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
ViewDataViewBag
键值对动态类型
索引ViewData的封装
支持任意类型动态属性
TempDataCacheSession
视图级别应用程序级别会话级别
只允许消费一次服务器端保存服务器端保存
可多次赋值可设置有效期键值对形式
键值对形式键值对形式 
  • 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文件
        • 配置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
<!-- 依赖框架的部署 (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>
    ...
    ...
    ...

源码地址

  • DncLesson

 到此这篇关于asp.net CORE基础教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: ASP.NET CORE基础教程

本文链接: https://www.lsjlt.com/news/163277.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • ASP.NET CORE基础教程
    目录第一课 基本概念第二课 控制器的介绍第三课 视图与表单第四课 数据验证第五课 路由规则第六课 应用发布与部署源码地址第一课 基本概念 基本概念Asp.Net Core Mvc是....
    99+
    2022-11-13
  • ASP.NET Core基础之Startup类
    ASP.NET Core必须包含Startup类。它就像 Global.asax 文件,我们传统的 .NET 应用程序。如名称建议的那样,在应用程序启动时首先执行它。在程序类的Mai...
    99+
    2022-11-13
  • EF Core基础入门教程
    EF Core 是一个ORM(对象关系映射),它使 .NET 开发人员可以使用 .NET对象操作数据库,避免了像ADO.NET访问数据库的代码,开发者只需要编写对象即可。 EF Co...
    99+
    2022-11-13
  • ASP.NET Core基础之Main方法讲解
    为什么ASP.NET Core采用Main方法? 需要记住的最重要的一点是,ASP.NET Core Web 应用程序最初作为控制台应用程序启动,Main() 方法是应用程序的入口点...
    99+
    2022-11-13
  • ASP.Net Core MVC基础系列之项目创建
    一 : 系列教程环境介绍 1: 操作系统, Windows 10 专业版 64位 (版本号: 1809) 2: IDE使用Visual Studio 2017专业版 (版本号: 15...
    99+
    2022-11-13
  • ASP.Net Core MVC基础系列之环境设置
    上一节我们介绍了中间件的基本使用, 这一节我们讲一讲.Net Core的环境设置, 以及根据不同的环境加载不同的配置信息 PS: 由于最近一直比较忙, 一直没抽时间更新这个系列, 最...
    99+
    2022-11-13
  • ASP.NET Core Web API 教程Project Configuration
    目录1. 创建新项目2. launchSettings.json 文件3. Program.cs 和 Startup.cs4. 扩展方法和 CORS 配置5. IIS 配置6. St...
    99+
    2022-11-12
  • ASP.NET Core快速入门教程
    目录第一课 基本概念第二课 控制器的介绍第三课 视图与表单第四课 数据验证第五课 路由规则第六课 应用发布与部署源码地址第一课 基本概念 基本概念Asp.Net Core Mvc是....
    99+
    2022-11-13
  • Redis数据库基础与ASP.NET Core缓存实现
    目录基础Redis 库连接 Redis能用 redis 干啥Redis 数据库存储字符串订阅发布RedisValueASP.NET Core 缓存与分布式缓存内存中的缓存ASP.NE...
    99+
    2022-11-13
  • ASP.Net Core MVC基础系列之获取配置信息
    这一节, 我们来讲解.Net Core 是怎么获取配置信息的. .Net Core配置信息来源主要有以下几种 1.appsettings.json文件2. User Secrets3...
    99+
    2022-11-13
  • Python基础教程
    6.4.5 参数收集的逆过程 假设有如下函数: def add(x,y): return x+y 比如说有个包含由两个相加的数字组成的元组: params = (1,2) 使用*运算符对参数进行“分配”,不过是在调用而不是在定义时使用: ...
    99+
    2023-01-31
    基础教程 Python
  • JavaScript 基础教程 (转)
    JavaScript 基础教程 (转)[@more@]Javascript 基础教程XML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" />今天时间...
    99+
    2023-06-03
  • Python Numpy-基础教程
    目录 1. 为什么要学习numpy 2. Numpy基本用法 2.1. 创建np.ndarry 2.2. Indexing and ...
    99+
    2023-01-30
    基础教程 Python Numpy
  • OpenMV零基础教程
    一、资料导航         “工欲善其事,必先利其器”。在正式学习OpenMV之前,你必须知道一条或几条OpenMV的学习途径。这里推荐星瞳科技的中文官网教程,这个教程里面包括了OpenMV IDE的下载和安装、OpenMV上手教程、Op...
    99+
    2023-08-31
    python stm32
  • python入门基础教程
    Python是一门简单易学、功能强大的编程语言,适合初学者入门。下面是一个简要的Python入门基础教程,帮助您快速上手Python编程。1. 安装Python:首先,您需要在计算机上安装Python解释器。您可以从Python官方网站(h...
    99+
    2023-10-25
    python 入门 基础教程
  • Gstreamer基础知识教程
    目录一、Gstreamer整体框架二、Gstreamer基础概念由于deepstream是基于gstreamer的,所以要想在deepstream上做拓展,需要对gstreamer有...
    99+
    2022-11-13
  • JavaStream流零基础教程
    目录一、Stream流介绍二、Stream流实现与传统方式实现对比2.1、传统方式实现2.2、Stream流方式实现三、Stream流的常用API3.1、stream流的获取3.2、...
    99+
    2022-11-13
    Java Stream流 Java Stream
  • mongodb 基础入门教程
    算是学习下来精炼的笔记,希望对大家有帮助。如果有问题欢迎大家指正。 0.概述 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。 在高负载的情况下,添加更多的节点,可以保证服务器性能。 MongoDB 旨在为W...
    99+
    2015-07-29
    mongodb 基础入门教程
  • Python3 基础语法教程
    编码默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 当然你也可以为源码文件指定不同的编码: 上述定义允许在源文件中使用 Windows-1252 字符集中的字符编码,对应适合语言为保加...
    99+
    2023-01-31
    语法 基础 教程
  • JavaScriptTypescript基础使用教程
    目录简介安装安装命令使用原因TypeScript类型概述JS原有的类型TS新增的类型类型别名泛型简介 typescript是微软公司开发的开源编程语言,Type+Javascript...
    99+
    2022-12-08
    JavaScript Typescript JS Typescript基本使用
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作