![](/img/trans.png)
[英]Silverlight Security Concern when Dynamically Setting Connection String with Entity Framework
[英]Silverlight Entity Framework Dynamic Connection String
我在一堆不同的服务器上有相同的数据模型。 我想根据用户是谁以及他们在做什么动态创建连接字符串。
我的用户可以在多个服务器上拥有多个数据库。 创建DomainService时,我需要一种干净的方法来构建连接字符串。
我看到DomainService有一个重写(继承自LinqToEntitiesDomainService),称为CreateObjectContext(),它将允许我设置所需的任何连接字符串,然后返回新实体,并且生活很美好。 问题是,CreateObjectContext()在构造函数之后被调用,所以我无法通过invoke方法设置字符串。 另外,我尝试在DomainService上创建一个新的参数化构造函数,但从未将其复制到客户端上的DomainContext中。
如果我能够拉出我的连接字符串,CreateObjectContext()会很好用,但是由于我必须使用来自客户端的数据来确定要连接的数据库,所以这显然行不通。
我考虑的越多,我就越觉得自定义构造函数正是我所需要的-只是不知道如何完成该工作。
我想念什么?
我找到了解决方案。 对于那些感兴趣的人,这里是:
感觉有点像黑客,但这是我能想到的唯一解决方案。 感谢Sally Xu在forums.silverlight.net上获得的想法。
由于我的每个用户都可以在多个服务器上拥有多个数据库,因此我需要在首次使用DomainService之前找到一种创建ConnectionString的方法。 每次用户从UI中选择一个新项目时,我都会设置如下cookie:
private void SetCookie(string cookieName, string cookieValue)
{
DateTime expireDate = DateTime.Now + TimeSpan.FromDays(1);
string newCookie = cookieName + "=" + cookieValue + ";expires=" + expireDate.ToString("R");
HtmlPage.Document.SetProperty("cookie", newCookie);
}
cookieName是SelectedProjectId
,而cookieValue是UI中当前选择的项目。
然后,像往常一样创建一个新的DomainService,但是我覆盖了CreateObjectContext()
。 首次引用DomainService对象时,将调用此方法。 我的覆盖看起来像这样:
protected override ProjectEntities CreateObjectContext()
{
long projectId = -1;
StringBuilder connection;
if (System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"] != null)
{
projectId = Convert.ToInt64(System.Web.HttpContext.Current.Request.Cookies["SelectedProjectId"].Value);
}
else throw new Exception("Selected Project ID Exception"); // temporary
// Verify this user has access to the DB just in case it's spoofed
// Lookup project ID in my database to get the database name and server name
// Load template connection string found in web.config
// Replace the template holders for SERVER_NAME and DATABASE_NAME with above lookup values
return new ProjectEntities(MyDynamicConnectionString);
}
再说一次,这有点骇人听闻,但这是我可以找到动态创建满足我需求的连接字符串的唯一方法。 我希望这可以帮助其他人...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.