'How to use CACHE_URL and SCRIPT_NAME IIS URL Rewrite Module server variable while setting Rewrite Rules through middleware in .NET 6.0?

We are moving a .NET framework application to .NET 6.0 and for that, I have moved Rewrite Rules from web.config to a separate XML file, and the configuration is done through middleware.

In my current web.config file, there are two server variables (CACHE_URL, SCRIPT_NAME) that are not supported by the middleware. This is also stated in Microsoft's Rewrite rule documentation where CACHE_URL and SCRIPT_NAME server variables are not in the list of supported variables.

My code goes like this:

From Startup.cs

using (StreamReader iisUrlRewriteStreamReader =
            File.OpenText(string.Format(@"{0}\IISUrlRewrite.xml", System.AppDomain.CurrentDomain.BaseDirectory)))
            {
                var options = new RewriteOptions()
                    .AddIISUrlRewrite(iisUrlRewriteStreamReader);

                app.UseRewriter(options);
            }

From IISUrlRewrite.xml

<rewrite>
      <rules>
<rule name="SignalRProxyRule" stopProcessing="true">
          <match url="signalr(/.*)*" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{CACHE_URL}" pattern="^(.+)://" />
          </conditions>
          <action type="Rewrite" url="http://localhost:8082/{R:0}" logRewrittenUrl="true" />
        </rule>
<rule name="StaticContentProxyRule" enabled="true" stopProcessing="true">
          <match url="(?:\.css|\.js|\.html|\.ttf|\.jpg|\.png|\.gif|\.svg|\.json|\.woff|\.woff2)$" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="static/{SCRIPT_NAME}" />
        </rule>
      </rules>
</rewrite>

The following exceptions are thrown once I run the application:

System.FormatException: 'Unrecognized parameter type: 'CACHE_URL'/'', terminated at string index: '10''

System.FormatException: 'Unrecognized parameter type: 'SCRIPT_NAME'/'', terminated at string index: '66''

Is there any workaround for using CACHE_URL and SCRIPT_NAME server variables when configuring Rewrite rules through middleware?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source