在ASP.NET中使用三層架構(Presentation Layer, Business Logic Layer, Data Access Layer)可以提高應用程序的可維護性、可擴展性和安全性。以下是一些確保三層架構安全性的建議:
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "SELECT * FROM Users WHERE UserId = @UserId";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@UserId", userId);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// 處理數據
}
}
}
using (TransactionScope scope = new TransactionScope())
{
try
{
// 數據訪問代碼
// 業務邏輯代碼
scope.Complete();
}
catch (Exception ex)
{
// 處理異常
}
}
[Authorize]
public class AccountController : Controller
{
// 控制器方法
}
public class Global : System.Web.HttpApplication
{
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// 記錄異常日志
}
}
ProtectedConfigurationProvider
保護配置文件,防止敏感信息泄露。<configuration>
<configSections>
<section name="connectionStrings" type="System.Configuration.ClientSectionHandler" />
</configSections>
<connectionStrings configSource="Web.config" />
</configuration>
通過遵循上述建議,可以有效地提高ASP.NET三層架構的安全性。