ASP.NET Core快速入门教程

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

第一课 基本概念

基本概念Asp.Net Core Mvc是.NET Core平台下的一种Web应用开发框架符合Web应用特点.NET Core跨平台解决方案MVC设计模式的一种实现环境准备安装最新版Visual Studio 2017安装最新版.NET Core Sdk

第二课 控制器的介绍

控制器定义方式:命名以Controller结尾使用ControllerAttribute标注
    public class TestController : Controller    {    }    [Controller]    public class Test : Controller    {    }

默认路由规则

域名/控制器类/方法{Domain}/{Controller}/{Action}

数据形式

QueryString: ?name=zhangsan&age=22FormCookieSessionHeader

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");        }
HttpContextHttpContext是用户请求上下文提供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:文本内容

第三课 视图与表单

数据传递ViewDataViewBagtempDataModelSessionCache
ViewDataViewBag
键值对动态类型
索引器ViewData的封装
支持任意类型动态属性
TempDataCacheSession
视图级别应用程序级别会话级别
只允许消费一次服务器端保存服务器端保存
可多次赋值可设置有效期键值对形式
键值对形式键值对形式 
Cache与.NET Framework时代不同,一种全新实现IMemoryCaeturns> 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); }

常用数据验证

RequiredAttributeRegularExpressionAttributeCompareAttributeRangeAttributeMaxAttributeMinAttributeStringLengthAttributeDataTypeAttribute

服务器端使用

使用包含验证规则的类接收数据使用ModelState.IsValid判断是否符合要求

前端使用

定义强类型视图并传递包含验证规则的业务数据模型使用HtmlHelper.ValidationFor初始前端验证规则使用HtmlHelper.ValidationMessageFor生成提示文字
    public class UserLoginVgYtotl    {        [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类型
lengthVgYtotl"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>
部署IIS 部署目标机器安装对应版本的.NET Core Sdk安装.NET Core Windows Server 托管程序应用程序池的“.NET CLR版本”设置为“无托管代码”ASP.NETCore快速入门教程自宿主发布发布成一个exe直接运行不用依赖IISRuntimeIdentifier.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快速入门教程的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。