ttugates
ttugates

Reputation: 6291

Rewrite Rule to IIS for HTTPS redirect to HTTP causes null HttpContext.Request.ContentType

I am using HTTPS redirect site extension for Azure which has an applicationhost.xdt like this:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <location path="%XDT_SITENAME%" xdt:Transform="InsertIfMissing" xdt:Locator="Match(path)">
        <system.webServer xdt:Transform="InsertIfMissing">
            <rewrite xdt:Transform="InsertIfMissing">
                <rules xdt:Transform="InsertIfMissing">
                    <rule name="redirect HTTP to HTTPS" enabled="true" stopProcessing="true" xdt:Transform="InsertIfMissing" xdt:Locator="Match(name)">
                        <match url="(.*)" />
                        <conditions>
                            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                            <add input="{WARMUP_REQUEST}" pattern="1" negate="true" />
                        </conditions>
                        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </location>
</configuration>

I am getting null for HttpContext.Request.ContentType when Postman sends to HTTP instead of HTTPS and the above takes effect.

I test with this middleware like so:

public class TestMiddleware
{
    readonly RequestDelegate _next;

    public TestMiddleware(RequestDelegate next)
    {
        if (next == null) throw new ArgumentNullException(nameof(next));
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException(nameof(httpContext));
        }

        var requestContentType = httpContext.Request.ContentType;
        await httpContext.Response.WriteAsync($"requestContentType: {requestContentType}");
    }
} 

I'd prefer to continue handling HTTP redirect in IIS as opposed to the common middleware solution for .Net Core.

Does anyone know a parameter to add to applicationhost.xdt to address?

Update 1: For clarity:

This issue reproduces only when I call HTTP and a redirect to HTTPS occurs.

Conversely, when I call using HTTPS I get the expected Request.ContentType result.

Using the solution provided in this Answer below, I get the same behavior. I am no longer sure the solution will be an edit to applicationhost.xdt. Perhaps I need to get the Request.ContentType another way?

Upvotes: 1

Views: 662

Answers (1)

David Ebbo
David Ebbo

Reputation: 43193

Note that there is now a much simpler way of redirecting http traffic to https: under Custom domains, just set HTTPS Only to On. Then you don't need any site extension or xdt file.

See this post for more info.

Upvotes: 3

Related Questions