Azure App Service槽位设置如何在web.config中使用的技术问询
Absolutely! You can leverage Azure App Service slot-specific app settings directly in your web.config—you just need to use the syntax that IIS natively recognizes. Here's how to make it work:
1. Use IIS Environment Variable Syntax
IIS supports referencing environment variables (including Azure App Service app settings, which are exposed as environment variables) using the %VARIABLE_NAME% format. This works directly in your web.config XML without any extra code.
Example: Slot-Specific Redirect Rule
Suppose you have a slot setting named ENV_EXTERNAL_HOST (make sure you check the "Deployment slot setting" box when creating it so it doesn't get overwritten during slot swaps). You can reference it in a rewrite rule like this:
<system.webServer> <rewrite> <rules> <rule name="Slot-Specific External Redirect" stopProcessing="true"> <match url="^go/external/(.*)" /> <action type="Redirect" url="https://%ENV_EXTERNAL_HOST%/{R:1}" redirectType="Temporary" /> </rule> </rules> </rewrite> </system.webServer>
Example: Slot-Specific Proxy Target
For reverse proxy scenarios (using ARR), you can use the same syntax to target different backend URLs per slot:
<system.webServer> <rewrite> <rules> <rule name="Proxy to Slot-Specific Backend" stopProcessing="true"> <match url="^api/(.*)" /> <action type="Rewrite" url="https://%ENV_PROXY_TARGET%/api/{R:1}" /> </rule> </rules> </rewrite> </system.webServer>
2. Key Notes to Make This Work
- Match Setting Names Exactly: Ensure the variable name in
%...%matches the name of your slot-specific app setting (it's case-insensitive in IIS, but it's best to keep them consistent to avoid confusion). - Mark as Slot Settings: When creating or editing the app setting in Azure Portal, check the Deployment slot setting checkbox. This ensures the setting is unique to the slot and won't be swapped with another slot.
- Restart the Slot (If Needed): After updating slot settings, you might need to restart the app slot for the changes to take effect in
web.config.
Alternative for .NET Apps (If Needed)
If you're working with an ASP.NET (Framework or Core) app, you can also read slot settings via ConfigurationManager.AppSettings (Framework) or IConfiguration (Core) and dynamically apply configuration in code. But the IIS environment variable method is simpler if you just need to tweak web.config elements like rewrite rules or proxy targets.
This approach keeps your web.config generic across all slots, letting you manage environment-specific values directly through Azure's slot settings—no need to maintain multiple versions of the config file!
内容的提问来源于stack exchange,提问作者Michał Fronczyk

