ASP.NET?Core快速入門教程
更新時間:2022年02月16日 11:16:58 作者:Kindyroo(袋鼠)
這篇文章介紹了ASP.NET?Core快速入門教程,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
第一課 基本概念
- 基本概念
- Asp.Net Core Mvc是.NET Core平臺下的一種Web應用開發(fā)框架
- 符合Web應用特點
- .NET Core跨平臺解決方案
- MVC設計模式的一種實現
- Asp.Net Core Mvc是.NET Core平臺下的一種Web應用開發(fā)框架
- 環(huán)境準備
- 安裝最新版Visual Studio 2017
- 安裝最新版.NET Core Sdk
第二課 控制器的介紹
- 控制器定義方式:
- 命名以
Controller結尾 - 使用
ControllerAttribute標注
- 命名以
public class TestController : Controller
{
}
[Controller]
public class Test : Controller
{
}默認路由規(guī)則
- 域名/控制器類/方法
{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");
}- 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");
}- 數據綁定
- 把用戶請求的數據綁定到控制器方法的參數上
- 支持簡單類型與自定義類型
- 綁定規(guī)則是請求數據名稱與參數名稱一致
- 如查詢字符串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結尾的都是控制器,那如果程序里面由一些業(yè)務命名的時候也是以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 |
|---|---|
| 鍵值對 | 動態(tài)類型 |
| 索引器 | ViewData的封裝 |
| 支持任意類型 | 動態(tài)屬性 |
| 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命名,固定名稱,不能更換
- 一般放在視圖所在目錄的根目錄下
- 自動執(zhí)行,無需手工調用
- 不要再ViewStart中做大量的業(yè)務操作
- ViewImport
- 以_ViewImport.cshtml命名,固定名稱,不能更換
- 只作引入操作
- 一般放在視圖所在目錄的根目錄下
- 自動執(zhí)行,無需手工調用
- 視圖中可以使用@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
服務器端使用
- 使用包含驗證規(guī)則的類接收數據
- 使用ModelState.IsValid判斷是否符合要求
前端使用
- 定義強類型視圖并傳遞包含驗證規(guī)則的業(yè)務數據模型
- 使用HtmlHelper.ValidationFor初始前端驗證規(guī)則
- 使用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>第五課 路由規(guī)則
路由
- 定義用戶請求與控制器方法之前的映射關系
路由配置
- IRouteBuilder
- 通過MapRoute方法配置路由模板
- IRouteBuilder
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();
}第六課 應用發(fā)布與部署
- 發(fā)布
- 發(fā)布方法
- 使用
Visual Studio發(fā)布應用:項目右鍵 -> 發(fā)布 -> 發(fā)布方式選擇... - 使用
dotnet publish命令行工具發(fā)布:dotnet publish --configuration Release --runtime win7-x64 --output c:\svc
- 使用
- 發(fā)布方法
- 視圖預編譯
- 少了運行時編譯過程,啟動速度快
- 預編譯后,整個程序包更小
- 可以通過MvcRazorCompileOnPublish配置是否開啟,默認是開啟狀態(tài)
- 關閉視圖預編譯:
- 打開項目的
.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版本”設置為“無托管代碼”

- 自宿主發(fā)布
- 發(fā)布成一個exe直接運行
- 不用依賴IIS
- RuntimeIdentifier
- .NET Core RID Catalog
- IIS 部署
<!-- 依賴框架的部署 (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快速入門教程的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
連接ACCESS數據庫時發(fā)生錯誤提示:找不到可安裝的 ISAM
連接ACCESS數據庫時發(fā)生錯誤提示:找不到可安裝的 ISAM 檢查后發(fā)現原來是把Data Source寫成 DataSource了2011-04-04
.Net創(chuàng)建型設計模式之建造者、生成器模式(Builder)
這篇文章介紹了.Net設計模式之建造者、生成器模式(Builder),文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05

