Asp.Net Core 程序開發技巧匯總
阿新 • • 發佈:2019-01-03
amp 進行 rim expr eight 符號 book orm basedir
使用Sqlite數據庫
創建項目
Asp.Net Core Web應用程序
Web應用程序 ASP.NET Core 2.2
NuGet管理,添加Sqlite數據庫支持
Microsoft.EntityFrameworkCore.Sqlite
添加數據實體類
添加文件夾Models
在Models文件夾添加類 Test Context
using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; namespaceWebApplication1.Models { public class TestContext:DbContext { public TestContext(DbContextOptions<TestContext> options) : base(options) { } public DbSet<Person> People { get; set; } public DbSet<Book> Books { get; set; } } public class Person { [Display( Name ="編號")] public int PersonID { get; set; } [Display(Name ="姓名")] public string PersonName { get; set; } [Display(Name ="書籍")] public List<Book> Books { get; set; } } publicclass Book { [Display(Name ="編號")] public int BookID { get; set; } [Display(Name ="書名")] public string BookName { get; set; } [Display(Name ="人員編號")] public int PersonID { get; set; } [Display(Name ="人員")] public Person Person { get; set; } } }
更改Startup.cs文件
添加引用
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Sqlite;
更新以下過程
public void ConfigureServices(IServiceCollection services) { …… //實現註入 var dbpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test.db"); var connstr = $"Data Source={dbpath}"; services.AddDbContext<TestContext>(options => options.UseSqlite(connstr)); //自動創建數據庫 var builder = new DbContextOptionsBuilder<TestContext>(); builder.UseSqlite(connstr); using (var db = new TestContext(builder.Options)) { db.Database.EnsureCreated(); } …… }
添加Razor頁面實現數據的增刪改查
在Pages目錄增加子目錄 People和Books
在People目錄右擊鼠標,選擇添加 新搭建基架的項目
選擇使用實體框架生成Razor頁面(CRUD)
在Books目錄右擊鼠標,選擇添加 新搭建基架的項目
選擇使用實體框架生成Razor頁面(CRUD)
安裝配置 Session
NuGet 添加引用
Microsoft.AspNetCore.Session
Session 是基於 IDistributedCache 構建的,所以必須引用一種 IDistributedCache 的實現,ASP.NET Core 提供了多種 IDistributedCache 的實現 (Redis、SQL Server、In-memory)
修改Startup.cs文件
public void ConfigureServices(IServiceCollection services) { …… services.AddDistributedMemoryCache(); services.AddSession(); …… } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { …… app.UseSession(); …… }
使用Session
設置Session變量
public async Task OnGetAsync() { Book = await _context.Books .Include(b => b.Person).ToListAsync(); var s = "hello world @ " + DateTime.Now.ToString(); var b1 = System.Text.Encoding.UTF8.GetBytes(s); HttpContext.Session.Set("key1", b1); }
讀取Session變量
public async Task OnGetAsync() { Person = await _context.People.ToListAsync(); byte[] data; var b = HttpContext.Session.TryGetValue("key1", out data); var s = System.Text.Encoding.UTF8.GetString(data); ViewData["key1"] = s; }
通過字段屬性實現數據校驗
字段屬性使用範例
[Display(Name ="分組編號")] public int GroupID { get; set; } [Display(Name ="分組名稱")] [Required(ErrorMessage = "分組名稱不能為空")] [RegularExpression(@"^[a-zA-Z]+[0-9]*", ErrorMessage = "只能使用英文字母和數字,並且第一個符號必須為英文字母。")] [StringLength(20,MinimumLength =3,ErrorMessage ="最短長度3,最大長度20")] public string GroupName { get; set; } [Display(Name ="學生列表")]
頁面直接顯示字段屬性
列標題
@Html.DisplayNameFor(model => model.Administrator[0].UserName)
數據行
@Html.DisplayFor(modelItem => item.UserName)
使用正則表達式實現復雜校驗
[RegularExpression(@"^[a-zA-Z]+[0-9]*", ErrorMessage = "只能使用英文字母和數字,並且第一個符號必須為英文字母。")]
自定義錯誤提示
ModelState的屬性
這是一個類型為ModelStateDictionary的ModelState類型的字典集合。在進行數據驗證的時候這個屬性是比較實用的。在使用Html.ValidationMessage()的時候,就是從ViewData.ModelState中檢測是否有指定的KEY。假設存在。就提示錯誤信息。
ModelState.AddModelError("LoginError", "登錄失敗");
頁面上增加以下代碼:
<span class="text-danger">@Html.ValidationMessage("LoginError")</span>
實現登錄功能
添加Razor頁面
頁面代碼如下:
@page @model CourseAssistant.Pages.Login.IndexModel @{ ViewData["Title"] = "登錄"; } <h1>登錄</h1> <hr /> <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="LoginEntry.UserName" class="control-label"></label> <input asp-for="LoginEntry.UserName" class="form-control" /> <span asp-validation-for="LoginEntry.UserName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="LoginEntry.Password" class="control-label"></label> <input asp-for="LoginEntry.Password" class="form-control" /> <span asp-validation-for="LoginEntry.Password" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="登錄" class="btn btn-primary" /> <span class="text-danger">@Html.ValidationMessage("LoginError")</span> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
更新IndexModel代碼
public class IndexModel : PageModel { private readonly CourseAssistant.Models.CourseAssistantContext _context; public IndexModel(CourseAssistant.Models.CourseAssistantContext context) { _context = context; } [BindProperty] public LoginEntry LoginEntry { get; set; } public void OnGet() { } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var admin = await _context.Administrators.FirstOrDefaultAsync(m => m.UserName == LoginEntry.UserName && m.Password == LoginEntry.Password); if (admin != null) { this.SetCurrentUser(new LoginUser() { UserTyep = UserType.Administrator, Administrator = admin, Student = null }); return RedirectToPage("/Groups/Index"); } else { ModelState.AddModelError("LoginError", "登錄失敗"); return Page(); } } } public class LoginEntry { [Display(Name ="賬號")] [Required(ErrorMessage = "用戶名不能為空。")] [RegularExpression("^[a-zA-z]+[a-zA-z0-9]*",ErrorMessage ="只能使用英文和數字,並且第一個符號必須是英文")] [StringLength(20,MinimumLength =3,ErrorMessage="最大長度20,最小長度3")] public string UserName { get; set; } [Required(ErrorMessage = "密碼不能為空。")] [DataType(DataType.Password)] [Display(Name = "密碼")] [StringLength(20, MinimumLength = 3, ErrorMessage = "最大長度20,最小長度3")] public string Password { get; set; } }
實現文件上傳功能
添加Razor頁面
頁面代碼如下:
@page @model CourseAssistant.Pages.FileUploads.IndexModel @{ ViewData["Title"] = "文件上傳"; } <h2>文件上傳</h2> <hr /> <div class="row"> <div class="col-md-4"> <form method="post" enctype="multipart/form-data"> <div class="form-group"> <label asp-for="FileUpload.FileName" class="form-control"></label> <input asp-for="FileUpload.FileName" type="text" class="form-control" /> <span asp-validation-for="FileUpload.FileName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="FileUpload.FileData" class="form-control"></label> <input asp-for="FileUpload.FileData" type="file" class="form-control" style="height:auto;" /> <span asp-validation-for="FileUpload.FileData" class="text-danger"></span> </div> <input type="submit" value="上傳" class="btn btn-primary" /> </form> </div> </div>
更新IndexModel代碼
public class IndexModel : PageModel { public void OnGet() { } [BindProperty] public FileUpload FileUpload { get; set; } public async Task<IActionResult> OnPost() { var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Uploads"); if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } path = System.IO.Path.Combine(path, $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}_{FileUpload.FileData.FileName}"); var fs = System.IO.File.Open(path, System.IO.FileMode.Create, System.IO.FileAccess.Write); await FileUpload.FileData.CopyToAsync(fs); fs.Close(); fs.Dispose(); return Page(); } } public class FileUpload { [Required(ErrorMessage ="文件名不能為空")] [Display(Name ="文件名")] public string FileName { get; set; } [Required(ErrorMessage = "必須選擇需要上傳的文件")] [Display(Name ="選擇文件")] public IFormFile FileData { get; set; } }
Asp.Net Core 程序開發技巧匯總