本文介绍了如何在类中获取 ConnectionString 表单 appsettings.json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图连接到我的数据库而不对连接字符串进行硬编码.这就是我想出来的,有没有什么聪明的方法来获取ConnectionString?
I am trying to connect to my database without hardcoding the connectionstring. This is what Ive come up with, is there any smart way to get the ConnectionString?
SecurityDAO 类:
SecurityDAO class:
public class SecurityDAO
{
internal bool FindByUser(UserModel user)
{
string connectionString = "";
bool success = false;
string queryString = "SELECT * FROM users WHERE username = @username AND password = @password";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
MySqlCommand command = new MySqlCommand(queryString, connection);
command.Parameters.Add("@username", MySqlDbType.VarChar, 50).Value = user.Username;
command.Parameters.Add("@password", MySqlDbType.VarChar, 50).Value = user.Password;
try
{
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
success = true;
}
else
{
success = false;
}
}
catch (Exception ex)
{
throw ex;
}
}
return success;
}
}
SecurityService 类:
SecurityService class:
public class SecurityService
{
SecurityDAO daoService = new SecurityDAO();
public bool Authenticate(UserModel user)
{
return daoService.FindByUser(user);
}
}
推荐答案
您可以在使用 SecurityService 的地方使用 DI 获取 IConfiguration 并将 IConfiguration 传递给 SecurityService.Authenticate.这是一个演示:
You can use DI to get IConfiguration in somewhere you use SecurityService and pass IConfiguration to SecurityService.Authenticate.Here is a demo:
Startup.cs:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(Configuration);
services.AddScoped<SecurityService, SecurityService>();
}
控制器:
public class Test2Controller : Controller
{
IConfiguration _Configuration;
SecurityService _securityService;
public Test2Controller(IConfiguration Configuration, SecurityService securityService) {
_Configuration = Configuration;
_securityService = securityService;
}
public IActionResult Index()
{
var s=_securityService.Authenticate(new UserModel(), _Configuration);
return Ok();
}
}
安全服务:
SecurityDAO daoService = new SecurityDAO();
public bool Authenticate(UserModel user,IConfiguration Configuration)
{
return daoService.FindByUser(user, Configuration);
}
SecurityDAO:
SecurityDAO:
public class SecurityDAO
{
internal bool FindByUser(UserModel user, IConfiguration Configuration)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
return true;
}
}
结果:
这篇关于如何在类中获取 ConnectionString 表单 appsettings.json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!