重定向到HTTPS [英] Redirect to HTTPS

查看:174
本文介绍了重定向到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);
    }
});

这样做只是抓取整个网址,查询字符串等等,并使用 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天全站免登陆