[英]How to pass connection string as parameter using GET?
I have a asp.net web api and I need to get email list from the database. 我有一个asp.net Web API,我需要从数据库中获取电子邮件列表。 I need to pass the database connection string as parameter. 我需要将数据库连接字符串作为参数传递。 I know it is not safe to pass connection string like that, but that's the requirement. 我知道这样传递连接字符串并不安全,但这是必需的。 Whenever I pass in the connection string, the Rest client gives me 404 - Not Found. 每当我传入连接字符串时,Rest客户端都会给我404-未找到。 But I set the connection string within the database class, it's working. 但是我在数据库类中设置了连接字符串,它可以正常工作。 So how can I pass the connection as string and make it to retrieve the emails from database? 那么如何将连接作为字符串传递并使其从数据库中检索电子邮件?
Code to retrieve data from db 从数据库检索数据的代码
public List<EmailContacts> getEmailContacts(string connstr)
{
List<EmailContacts> emailList = new List<EmailContacts>();
MySqlDataReader rdr = null;
MySqlConnection myconn = new MySqlConnection(connstr);
String sqlstr = "SELECT * FROM emailcontacts";
MySqlCommand cmd = new MySqlCommand(sqlstr, myconn);
myconn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
EmailContacts e = new EmailContacts();
e.Id = rdr.GetInt32(0);
e.Name = rdr.GetString(1);
e.Email = rdr.GetString(2);
emailList.Add(e);
}
rdr.Close();
myconn.Close();
myconn.Dispose();
return emailList;
}
Get Api 获取Api
[HttpGet]
[Route("api/EmailContacts/{connstr}")]
public List<EmailContacts> Get(string connstr)
{
SalesDBConn db = new SalesDBConn();
return db.getEmailContacts(connstr);
}
This is how I tried to pass the connection string in the rest client 这就是我尝试在其余客户端中传递连接字符串的方式
http://localhost:59547/api/EmailContacts/server = example.com; uid = myusername; pwd = mypassword; database = mydb_example
you need to URL Encode your parameter. 您需要对参数进行URL编码。 your request should be 您的要求应该是
http://localhost:59547/api/EmailContacts/server%20%3D%20example.com%3B%20uid%20%3D%20myusername%3B%20pwd%20%3D%20mypassword%3B%20database%20%3D%20mydb_exampl
and yes, this is extremely not secure. 是的,这是绝对不安全的。
Bring in HttpUtility and UrlEncode the parameter. 引入HttpUtility和UrlEncode参数。
This is very vulnerable to attacks though in future if your db is hosted online. 这很容易受到攻击,但是如果将来您的数据库是在线托管的。 What is the issue with storing it in the Api's app settings? 将其存储在Api的应用程序设置中有什么问题?
If there are multiple connection string possible you could store them on a shared db against the Api and call them by Id by passing a Guid as the Api param? 如果有多个连接字符串,您可以将它们存储在针对Api的共享数据库中,并通过将Guid作为Api参数来通过ID进行调用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.