重写UserNamePasswordValidator时如何传入连接字符串

时间:2013-05-09 10:33:15

标签: c# asp.net wcf

我在我的WCF服务中覆盖UserNamePasswordValidator,我想针对SQL数据库验证用户名和密码。无论如何将连接字符串传递给PasswordValidator类?我还应该提到我的类与主WCF服务分开。

public class MyCustomUserNameValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        //TODO: how to pass in connection string??
        connectionString = "Data Source=MyDataSource;Initial Catalog=MyCatalog;User ID=MyUserName;Password=MyPassword";

        // connect to database and validate crendentials...

        if (!valid)
        {
            throw new SecurityTokenException("Access Denied.");
        }
    }
}

配置部分:

<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyCompany.Services.Validation.MyCustomUserNameValidator, MyCompany.Services.Validation"/>

感谢。

1 个答案:

答案 0 :(得分:1)

您可以将connectionString存储在<appsettings>

中的配置文件中
<addkey="DbConnection" value ="Your Connection String"/>

并在MyCustomUserNameValidator中使用 作为

ConnectionString = ConfigurationSettings.WebConfig["DbConnection"].ToString();

*编辑: ConfigurationManager does actually read from the web.config. the exact solution was: ConfigurationManager.AppSettings["ConnectionString"]就是答案