简体   繁体   中英

Assign web.config settings based on URL

I have an asp.net/c# website that runs on a dev server and a prod server. We keep the code identical between both servers. Is it possible, based on the URL to assign different settings in the web.config (eg for error pages etc)

Ideally I want an IF statement in the web.config eg

if (url.contains "http://dev") {
            web.config += @'<customErrors mode="Off" />'
} else {
            web.config += @'<customErrors mode="On" defaultRedirect="~/web/error.aspx" />'
}

Application configuration files have no direct templating nor scripting support so the approach outlined in the question is not possible. Building configuration files per environment is better placed as part of a build process.

If you are using Visual Studio 2012+ (or 2010 with the Visual Studio Web Publish Update) then you can use web.config transformations to manage the difference configurations across your environments.

This can be made to work for Web Site projects as per the question using some creative thinking. Eg http://andrewtwest.com/2010/02/25/using-web-config-transformations-in-web-site-projects/ . Although this involves creating a separate project for configuration management, it is a considerably less complex approach to implementing a full build process outside of the IDE.

Using this approach, you have a master web.config which contains your base config that is common across environments. In addition, you have a web.config transform file per build configuration that applies transformations specific to that environment. In your case, this would be to turn off customErrors in dev.

More information available here: http://msdn.microsoft.com/en-us/library/vstudio/dd465318(v=vs.100).aspx

But the basic idea is make sure you have all the build configurations you need, then right click on your web.config and select add transforms. These are then applied when the site is deployed using the respective build configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM