最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ASP.NET?CORE基礎(chǔ)教程

 更新時(shí)間:2022年01月21日 14:36:41   作者:Run2948  
本文詳細(xì)講解了ASP.NET?CORE的基礎(chǔ)教程,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

第一課 基本概念

  • 基本概念
    • Asp.Net Core Mvc是.NET Core平臺(tái)下的一種Web應(yīng)用開發(fā)框架
      • 符合Web應(yīng)用特點(diǎn)
      • .NET Core跨平臺(tái)解決方案
      • MVC設(shè)計(jì)模式的一種實(shí)現(xiàn)
  • 環(huán)境準(zhǔn)備

第二課 控制器的介紹

  • 控制器定義方式:
    • 命名以Controller結(jié)尾
    • 使用ControllerAttribute標(biāo)注
    public class TestController : Controller
    {

    }

    [Controller]
    public class Test : Controller
    {

    }
  • 默認(rèn)路由規(guī)則

    • 域名/控制器類/方法
    • {Domain}/{Controller}/{Action}
  • 數(shù)據(jù)形式

    • QueryString: ?name=zhangsan&age=22
    • Form
    • Cookie
    • Session
    • Header
  • HttpRequest

    • HttpRequest 是用戶請(qǐng)求對(duì)象
    • 提供獲取請(qǐng)求數(shù)據(jù)的屬性
      • 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是用戶請(qǐng)求上下文
    • 提供Session屬性獲取Session對(duì)象
      • Session.Set 設(shè)置
      • Session.Remove 移除
      • Session.TryGetValue 獲取數(shù)據(jù)
        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");
        }
  • 數(shù)據(jù)綁定
    • 把用戶請(qǐng)求的數(shù)據(jù)綁定到控制器方法的參數(shù)上
    • 支持簡(jiǎn)單類型與自定義類型
    • 綁定規(guī)則是請(qǐng)求數(shù)據(jù)名稱與參數(shù)名稱一致
      • 如查詢字符串key名稱跟參數(shù)一致
      • Form表單名稱跟參數(shù)一致
        public IActionResult Hello(RequestModel request,int? age)
        {
            // 查詢字符串
            var test = Request.Query["test"];
            // 簡(jiǎn)單類型
            var userAge = age;
            // 自定義類型
            var name = request.Name;

            return Content("Hello");
        }

        public class RequestModel
        {
            public string Name { get; set; }       
        }
  • 內(nèi)容補(bǔ)充
    • 如果以Controller結(jié)尾的都是控制器,那如果程序里面由一些業(yè)務(wù)命名的時(shí)候也是以Controller結(jié)尾,怎么辦?
    • NonControllerAttribute
    /// <summary>
    /// 拍賣師控制類
    /// </summary>
    [NonController]
    public class AuctionController
    {

    }
  • 常用特性
特性數(shù)據(jù)源
FromHeaderAttribute請(qǐng)求頭數(shù)據(jù)
FromRouteAttribute路由數(shù)據(jù)
FromBodyAttribute請(qǐng)求體
FromFormAttribute表單數(shù)據(jù)
FromQueryAttribute查詢字符串
FromServicesAttribute服務(wù)注冊(cè)
        public IActionResult Say(
            [FromForm]string name,
            [FromQuery]int age,
            [FromHeader] string salt,
            [FromBody] string content
            )
        {
            return View();
        }
  • 特性參數(shù)

    • 通過特性修飾參數(shù)來影響綁定邏輯
    • 靈活擴(kuò)展
  • IActionResult

    • 動(dòng)作結(jié)果接口
    • 具體實(shí)現(xiàn)
      • JsonResult:返回JSON結(jié)構(gòu)數(shù)據(jù)
      • RedirectResult:跳轉(zhuǎn)到新地址
      • FileResult:返回文件
      • ViewResult:返回視圖內(nèi)容
      • ContentResult:文本內(nèi)容

第三課 視圖與表單

  • 數(shù)據(jù)傳遞
    • ViewData
    • ViewBag
    • tempData
    • Model
    • Session
    • Cache
ViewDataViewBag
鍵值對(duì)動(dòng)態(tài)類型
索引器ViewData的封裝
支持任意類型動(dòng)態(tài)屬性
TempDataCacheSession
視圖級(jí)別應(yīng)用程序級(jí)別會(huì)話級(jí)別
只允許消費(fèi)一次服務(wù)器端保存服務(wù)器端保存
可多次賦值可設(shè)置有效期鍵值對(duì)形式
鍵值對(duì)形式鍵值對(duì)形式 
  • Cache
    • 與.NET Framework時(shí)代不同,一種全新實(shí)現(xiàn)
    • IMemoryCache接口
    • 依賴注入方式獲取
    • IMemoryCache.Get/Set操作數(shù)據(jù)
    [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命名,固定名稱,不能更換
    • 一般放在視圖所在目錄的根目錄下
    • 自動(dòng)執(zhí)行,無需手工調(diào)用
    • 不要再ViewStart中做大量的業(yè)務(wù)操作
  • ViewImport
    • 以_ViewImport.cshtml命名,固定名稱,不能更換
    • 只作引入操作
    • 一般放在視圖所在目錄的根目錄下
    • 自動(dòng)執(zhí)行,無需手工調(diào)用
    • 視圖中可以使用@using關(guān)鍵字引入所需命名空間
    • 通過ViewImport做全局性的命名空間引入,減少在每個(gè)頁(yè)面中引入的工作量

第四課 數(shù)據(jù)驗(yàn)證

  • 數(shù)據(jù)驗(yàn)證特性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);
  }
  • 常用數(shù)據(jù)驗(yàn)證

    • RequiredAttribute
    • RegularExpressionAttribute
    • CompareAttribute
    • RangeAttribute
    • MaxAttribute
    • MinAttribute
    • StringLengthAttribute
    • DataTypeAttribute
  • 服務(wù)器端使用

    • 使用包含驗(yàn)證規(guī)則的類接收數(shù)據(jù)
    • 使用ModelState.IsValid判斷是否符合要求
  • 前端使用

    • 定義強(qiáng)類型視圖并傳遞包含驗(yàn)證規(guī)則的業(yè)務(wù)數(shù)據(jù)模型
    • 使用HtmlHelper.ValidationFor初始前端驗(yàn)證規(guī)則
    • 使用HtmlHelper.ValidationMessageFor生成提示文字
    public class UserLogin
    {
        [Required(ErrorMessage = "用戶名不能為空")]
        [StringLength(10,ErrorMessage = "用戶名長(zhǎng)度不能超過10位")]
        public string UserName { get; set; }
          
        //[Required(ErrorMessage = "密碼不能為空")]
        [StringLength(6,ErrorMessage = "密碼長(zhǎng)度不能超過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?"數(shù)據(jù)有效":"數(shù)據(jù)無效");
        }
    }
@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>

第五課 路由規(guī)則

  • 路由

    • 定義用戶請(qǐng)求與控制器方法之前的映射關(guān)系
  • 路由配置

    • 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
    • 應(yīng)用在控制器及方法上
    • 通過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?"數(shù)據(jù)有效":"數(shù)據(jù)無效");
        }
    }
  • 路由約束
    • 對(duì)路由數(shù)據(jù)進(jìn)行約束
    • 只有約束滿足條件才能匹配成功
約束示例說明
required"Product/{ProductName:required}"參數(shù)必選
alpha"Product/{ProductName:alpha}"匹配字母,大小寫不限
int"Product/{ProductId:int}"匹配int類型
·········
composite"Product/{ProductId:composite}"匹配composite類型
length"Product/{ProductName:length(5)}"長(zhǎng)度必須是5個(gè)字符
length"Product/{ProductName:length(5)}"長(zhǎng)度在5-10之間
maxlength"Product/{ProductId:maxlength(10)}"最大長(zhǎng)度為10
minlength"Product/{ProductId:minlength(3)}"最小長(zhǎng)度為3
min"Product/{ProductId:min(3)}"大于等于3
max"Product/{ProductId:max(10)}"小于等于10
range"Product/{ProductId:range(5,10)}"對(duì)應(yīng)的數(shù)組在5-10之間
regex"Product/{ProductId:regex(^\d{4}$)}"符合指定的正則表達(dá)式
  • 路由數(shù)據(jù)
    • 路由數(shù)據(jù)也是請(qǐng)求數(shù)據(jù)的一部分
    • 路由數(shù)據(jù)與表單數(shù)據(jù)一樣,也可以綁定到參數(shù)上
    • 默認(rèn)是通過名稱進(jìn)行匹配,也可以通過FormRouteAttribute匹配參數(shù)與路由數(shù)據(jù)的映射關(guān)系
    public IActionResult Index([FromRoute] int? id)
    {
        return View();
    }

第六課 應(yīng)用發(fā)布與部署

  • 發(fā)布
    • 發(fā)布方法
      • 使用Visual Studio發(fā)布應(yīng)用:項(xiàng)目右鍵 -> 發(fā)布 -> 發(fā)布方式選擇...
      • 使用dotnet publish命令行工具發(fā)布:dotnet publish --configuration Release --runtime win7-x64 --output c:\svc
  • 視圖預(yù)編譯
    • 少了運(yùn)行時(shí)編譯過程,啟動(dòng)速度快
    • 預(yù)編譯后,整個(gè)程序包更小
    • 可以通過MvcRazorCompileOnPublish配置是否開啟,默認(rèn)是開啟狀態(tài)
      • 關(guān)閉視圖預(yù)編譯:
        • 打開項(xiàng)目的.csproj文件
        • 配置MvcRazorCompileOnPublish為false
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <!-- 關(guān)閉視圖預(yù)編譯 -->
    <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>
<!-- 獨(dú)立部署 (SCD) -->
<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
</PropertyGroup>
    ...
    ...
    ...

源碼地址

 到此這篇關(guān)于ASP.NET CORE基礎(chǔ)教程的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 創(chuàng)建ASP.NET?Core?Web應(yīng)用程序并介紹項(xiàng)目模板

    創(chuàng)建ASP.NET?Core?Web應(yīng)用程序并介紹項(xiàng)目模板

    這篇文章介紹了創(chuàng)建ASP.NET?Core?Web應(yīng)用程序的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-02-02
  • c#中常用的js語句

    c#中常用的js語句

    有時(shí)候在開發(fā)中,經(jīng)常輸出一些js與客戶端實(shí)現(xiàn)交互,雖然說是c#的其實(shí)好多js的,需要的朋友可以收藏下。
    2010-04-04
  • 那些年,我還在學(xué)習(xí)asp.net(二) 學(xué)習(xí)筆記

    那些年,我還在學(xué)習(xí)asp.net(二) 學(xué)習(xí)筆記

    那些年覺得看視頻是很輕松的了解一個(gè)東西,但是這樣的不足就是感覺太慢了,沒有看書來得快,所以在有了一些了解后,還得看點(diǎn)書,也許書上的不一定好,但書上會(huì)把每一個(gè)應(yīng)該說到的地方說到,好有個(gè)初步的認(rèn)識(shí)
    2012-03-03
  • ASP.NET創(chuàng)建三層架構(gòu)圖解詳細(xì)教程

    ASP.NET創(chuàng)建三層架構(gòu)圖解詳細(xì)教程

    本文以圖片的形式完整演示了創(chuàng)建三層架構(gòu)的完整步驟,簡(jiǎn)單實(shí)用,希望能給大家一些幫助。
    2016-04-04
  • WCF入門需要掌握的基礎(chǔ)知識(shí)

    WCF入門需要掌握的基礎(chǔ)知識(shí)

    這篇文章介紹了WCF入門需要掌握的基礎(chǔ)知識(shí),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-01-01
  • ASP.NET Session使用詳解

    ASP.NET Session使用詳解

    Session是什么呢?簡(jiǎn)單來說就是服務(wù)器給客戶端的一個(gè)編號(hào)。當(dāng)一臺(tái)WWW服務(wù)器運(yùn)行時(shí),可能有若干個(gè)用戶瀏覽正在運(yùn)正在這臺(tái)服務(wù)器上的網(wǎng)站。
    2009-02-02
  • ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理介紹

    ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理介紹

    這篇文章介紹了ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • 讀取TXT文件內(nèi)容的方法

    讀取TXT文件內(nèi)容的方法

    讀取TXT文件內(nèi)容的方法...
    2006-10-10
  • Linux Ubuntu系統(tǒng)上手動(dòng)安裝.NET Core SDK的方法

    Linux Ubuntu系統(tǒng)上手動(dòng)安裝.NET Core SDK的方法

    .NET Core是一個(gè)開源通用的開發(fā)框架,支持跨平臺(tái),即支持在Window,macOS,Linux等系統(tǒng)上的開發(fā)和部署,并且可以在硬件設(shè)備,云服務(wù),和嵌入式/物聯(lián)網(wǎng)方案中進(jìn)行使用。下面這篇文章將給大家詳細(xì)介紹關(guān)于在Linux Ubuntu系統(tǒng)上手動(dòng)安裝.NET Core SDK的方法。
    2016-12-12
  • ASP.NET 中的Application詳解

    ASP.NET 中的Application詳解

    Application對(duì)象是HttpApplicationState類的一個(gè)實(shí)例,Application狀態(tài)是整個(gè)應(yīng)用程序全局的。本文主要詳細(xì)介紹Application對(duì)象的用法。
    2016-04-04

最新評(píng)論

铅山县| 绥芬河市| 綦江县| 黄骅市| 定日县| 富锦市| 富蕴县| 朝阳区| 内黄县| 临猗县| 蓝田县| 从江县| 铅山县| 高唐县| 上蔡县| 宜章县| 梧州市| 隆德县| 宾川县| 阿城市| 绥滨县| 蓝田县| 德钦县| 保亭| 乃东县| 买车| 锡林浩特市| 嘉义县| 黔江区| 自治县| 随州市| 利津县| 江陵县| 滕州市| 彝良县| 昭平县| 平果县| 长丰县| 南皮县| 东明县| 曲沃县|