Question

I have a Web Role that is using the ASP.NET SQL Membership provider. Currently the configuration is in the Web.Config file. I would like to configure the connection string as a Web Role setting instead of having it in the Web.Config. The main reason that I wan this is so that I can set up configurations on the azure project to publish to different hosted services (dev, qa, etc.) Right now, I have to manually edit the web.config each time I want to publish to a different service.

I have a couple ideas on how I might be able to accomplish this.

  1. Write a custom membership provider that wraps the SQL provider and provides custom configuration to it.
  2. Put something in the Web Role OnStart method to change the connection string in the Web.config file.

Has anyone done something like this before, or have recommendations on which option might be best, or have another idea on how to accomplish this?

Was it helpful?

Solution

The Windows Azure SDK allows you to have multiple service configurations per environment. But web.config modifications are a bit harder. In your case I would suggest you write some code (or a startup task) that reads the connection string from the service configuration and writes it to the web.config.

Andy's blog post 'Programmatically modify web.config on WebRole Startup' explains exactly how you can do this:

public override bool OnStart()
{
    using (var server = new ServerManager())
    {
        // get the site's web configuration
        var siteNameFromServiceModel = "Web"; // TODO: update this site name for your site. 
        var siteName =
            string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);
        var siteConfig = server.Sites[siteName].GetWebConfiguration();

        // get the appSettings section
        var appSettings = siteConfig.GetSection("appSettings").GetCollection();

        AddElement(appSettings, "deploymentId", RoleEnvironment.DeploymentId);
        AddElement(appSettings, "internalEndpointPort", RoleEnvironment.CurrentRoleInstance.InstanceEndpoints
            .First(t=>t.Key=="InternalEndpoint1").Value
            .IPEndpoint.Port.ToString());

        server.CommitChanges();
    }
    return base.OnStart();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top