You can use your own middleware class, but typically I just do something like this in my Startup configuration:
app.Use(async (context, next) =>
{
if (context.Request.IsHttps)
{
await next();
}
else
{
var withHttps = Uri.UriSchemeHttps + Uri.SchemeDelimiter + context.Request.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Scheme, UriFormat.SafeUnescaped);
context.Response.Redirect(withHttps);
}
});
What this does is just grab the entire URL, query string and all, and use GetComponents
to get everything except the scheme in the URL. Then the HTTPS scheme gets prepended to the components URL.
This will work with the full .NET Framework, for ASP.NET Core, you can do something like this:
app.Use(async (context, next) =>
{
if (context.Request.IsHttps)
{
await next();
}
else
{
var withHttps = "https://" + context.Request.Host + context.Request.Path;
context.Response.Redirect(withHttps);
}
});
This appends the host and the path to the HTTPS scheme. You may want to add other components such as the query and hash, too.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…