我正在尝试使用MongoDB作为ServiceStack的身份验证模块的持久性后端,因此我在web.config
中添加了以下节点:
<connectionStrings>
<add name="myDb" connectionString="mongodb://localhost/mydb?safe=true" />
</connectionStrings>
以下是我的Configure
方法:
public class MyAppHost : AppHostBase
{
public MyAppHost () : base("My Web Services", typeof(MyService).Assembly)
{
}
public override void Configure(Container container)
{
Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
new BasicAuthProvider()
}));
Plugins.Add(new RegistrationFeature());
var connectionString = ... // how do I retrieve "mongodb://localhost"?
var dbName = ... // how do I retrieve "mydb"?
var mongoClient = new MongoClient(connectionString);
var server = mongoClient.GetServer();
var db = server.GetDatabase(dbName);
container.Register<ICacheClient>(new MemoryCacheClient());
container.Register<IUserAuthRepository>(new MongoDBAuthRepository(db, true));
}
}
如何从web.config
中检索连接字符串和数据库名称?
答案 0 :(得分:1)
访问App或Web.Config appSettings的推荐方法是:
var appSettings = new AppSettings();
var connStr = appSettings.GetString("myDbConnectionString");
如果您将所有配置设置保留在<appSettings/>
标记中,那就是这样。
要访问<connectionStrings>
中保存的连接字符串,您可以使用ConfigUtils,例如:
var connStr = ConfigUtils.GetConnectionString("MyDb");