在ASP.NET中使用三層架構(也稱為MVC或MVVM模式)可以提高應用程序的安全性。以下是一些關鍵步驟和最佳實踐,可以幫助你提升三層架構的安全性:
public void InsertUser(User user)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Name", user.Name);
command.Parameters.AddWithValue("@Email", user.Email);
command.ExecuteNonQuery();
}
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet<User> Users { get; set; }
}
public void UpdateUser(User user)
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
context.Users.Update(user);
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
}
[HttpPost]
public IActionResult UpdateUser(User user)
{
if (ModelState.IsValid)
{
// 更新用戶邏輯
return RedirectToAction("Index");
}
return View(user);
}
public class ApplicationUser : IdentityUser
{
public string Role { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
// 配置角色和權限
}
通過遵循這些最佳實踐,你可以顯著提高ASP.NET三層架構的安全性。