c#三层结构写小程序后端登录接口
时间: 2023-09-01 22:06:27 浏览: 44
好的,以下是一个简单的C#三层结构写的小程序后端登录接口的示例:
1. 数据层(Data Access Layer)
```csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YourNamespace.Data
{
public class UserDataAccess
{
private readonly string connectionString;
public UserDataAccess(string connectionString)
{
this.connectionString = connectionString;
}
public bool ValidateUser(string username, string password)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "SELECT COUNT(*) FROM Users WHERE Username = @Username AND Password = @Password";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@Password", password);
connection.Open();
int count = (int) command.ExecuteScalar();
return count > 0;
}
}
}
}
}
```
2. 业务逻辑层(Business Logic Layer)
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YourNamespace.Data;
namespace YourNamespace.BusinessLogic
{
public class UserLogic
{
private readonly UserDataAccess userDataAccess;
public UserLogic(UserDataAccess userDataAccess)
{
this.userDataAccess = userDataAccess;
}
public bool ValidateUser(string username, string password)
{
return userDataAccess.ValidateUser(username, password);
}
}
}
```
3. 表现层(Presentation Layer)
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YourNamespace.BusinessLogic;
using YourNamespace.Data;
namespace YourNamespace.Presentation
{
class Program
{
static void Main(string[] args)
{
string connectionString = "your connection string";
UserDataAccess userDataAccess = new UserDataAccess(connectionString);
UserLogic userLogic = new UserLogic(userDataAccess);
Console.WriteLine("Please enter your username:");
string username = Console.ReadLine();
Console.WriteLine("Please enter your password:");
string password = Console.ReadLine();
if (userLogic.ValidateUser(username, password))
{
Console.WriteLine("Login successful!");
}
else
{
Console.WriteLine("Invalid username or password.");
}
Console.ReadLine();
}
}
}
```
注意,以上示例只是一个简单的演示,实际应用可能需要更严格的安全性和错误处理。