重定向到 HTTPS [英] Redirect to HTTPS

查看:35
本文介绍了重定向到 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将所有不安全的传入请求重定向到 HTTPS 的推荐方法是什么.我需要编写一个中间件组件吗?如果是这样,我无法弄清楚如何获取服务器名称.

What is the recommend way to redirect to HTTPS all incoming requests that are not secure. Do I need to write a middleware component? If so, I couldn't figure out how to get the server name.

public class RedirectHttpMiddleware
{
    RequestDelegate _next;

    public RedirectHttpMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.IsSecure)
            await _next(context);
        else
        {
            var server = "";  // How do I get the server name?
            context.Response.Redirect("https://" + server + context.Request.Path);
        }
    }
}

推荐答案

你可以使用你自己的中间件类,但通常我只是在我的启动配置中做这样的事情:

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);
    }
});

这只是获取整个 URL、查询字符串和所有内容,然后使用 GetComponents 获取 URL 中除方案之外的所有内容..然后将 HTTPS 方案添加到组件 URL 中.

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.

这将适用于完整的 .NET Framework,对于 ASP.NET Core,您可以执行以下操作:

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);
    }
});

这会将主机和路径附加到 HTTPS 方案.您可能还想添加其他组件,例如查询和哈希.

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.

这篇关于重定向到 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆