In my previous question the solution to my problem involved having to write an XML configuration file and then read it at startup: How to stop double redirect on https and www in ASP.NET Core 6?
In Program.cs I ended up with this:
app.UseRewriter(new RewriteOptions().AddIISUrlRewrite( app.Environment.WebRootFileProvider, "IISUrlRewrite.xml") );
Which works fine if the XML file is in wwwroot. I tried moving the XML file to the Content (Project) Root but nothing I change in the .csproj will cause it to just copy that file over to the server when I do a web deploy. It feels like the XML file is being compiled into the code.
I'd really like the file to live in a "Resources" folder and access it that way somehow.
Is there a way I can do that? Make a folder called Resources and access it through the API somehow? I need to get a StreamReader object to pass to the AddIISUrlRewrite function.
What am I doing wrong?
CodePudding user response:
OK, here's how I got it working. I have my IIS Url Rewrite rules that I took from web.config and I put them in an XML file called IISUrlRewrite.xml. I made a folder off the root of my web application project called Resources, and I put the XML file in there. Then I right-clicked on the file in the Solution Explorer and selected a Build Action of Embedded Resource.
Here are the contents of the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<rewrite>
<rules>
<clear />
<rule enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://example.com{REQUEST_URI}" appendQueryString="false" redirectType="308" />
</rule>
<rule enabled="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
<add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
</conditions>
<action type="Redirect" url="https://example.com/{R:1}" redirectType="308" />
</rule>
</rules>
</rewrite>
And this was the code I wrote in Program.cs to make it all work:
if (!app.Environment.IsDevelopment())
{
Assembly? ExecutingAssembly = Assembly.GetExecutingAssembly();
Stream? ManifestResourceStream = ExecutingAssembly!.GetManifestResourceStream(ExecutingAssembly.GetName().Name ".Resources.IISUrlRewrite.xml");
TextReader ResourceTextReader = new StreamReader(ManifestResourceStream!);
app.UseRewriter(new RewriteOptions().AddIISUrlRewrite(ResourceTextReader));
}
Now my HTTP->HTTPS and WWW->Non-WWW redirects all work perfectly on the production server.
