引言
ASP.NET Core 作為微軟推出的新一代Web開辟框架,以其跨平台、高機能跟模塊化計劃博得了眾多開辟者的青睞。本文將繚繞 ASP.NET Core 的實戰項目,從入門到進階,具體剖析其核心不雅點、關鍵技巧以及一些實用技能。
一、ASP.NET Core 入門
1.1 基本情況搭建
起首,妳須要在妳的開辟情況中安裝 .NET Core SDK 跟 Visual Studio Code 或 Visual Studio IDE。
1.2 創建第一個 ASP.NET Core 項目
利用以下命令創建一個簡單的 Web API 項目:
dotnet new webapi -n MyFirstApi
1.3 目錄構造
ASP.NET Core 項目存在以下目錄構造:
Controllers
:存放把持器類。Models
:存放數據模型類。Views
:存放 Razor 視圖文件。wwwroot
:存放靜態文件,如 CSS、JavaScript 跟圖片。
1.4 罕見命名標準
- 變數跟函數:小駝峰命名法(如
myVariable
)。 - 類:大年夜駝峰命名法(如
MyClass
)。
二、ASP.NET Core 實戰項目
2.1 材料庫操縱
利用 Entity Framework Core 停止材料庫操縱,實現增刪改查(CRUD)功能。
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=StudentDB;Trusted_Connection=True;");
}
}
2.2 非同步編程
利用 async/await 關鍵字實現非同步操縱,進步利用順序的機能。
public async Task<IActionResult> GetStudents()
{
var students = await _context.Students.ToListAsync();
return Ok(students);
}
2.3 靜態文件託管
在 wwwroot
目錄下存放靜態文件,如 CSS、JavaScript 跟圖片。
<link href="~/css/styles.css" rel="stylesheet" />
<script src="~/js/app.js"></script>
三、ASP.NET Core 進階技能
3.1 機能調優
- 增加材料庫查詢次數。
- 利用非同步編程形式。
- 避免適度利用 LINQ。
- 利用緩存機制。
3.2 旁邊件
自定義旁邊件以處理懇求跟呼應,如身份驗證、日記記錄等。
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var body = await new StreamReader(context.Response.Body).ReadToEndAsync();
context.Response.Body = new MemoryStream();
await _next(context);
context.Response.Body.Seek(0, SeekOrigin.Begin);
await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(body));
context.Response.Body.Seek(0, SeekOrigin.End);
}
}
3.3 保險性
利用身份驗證跟受權機制保護利用順序。
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});
四、總結
經由過程本文的講解,信賴妳曾經對 ASP.NET Core 有了一定的懂得。在現實開辟過程中,壹直現實跟積聚經驗是進步技能的關鍵。祝妳在 ASP.NET Core 之旅中一切順利!