将地址从HTTPS重写为HTTP

时间:2018-11-07 12:42:07

标签: c# asp.net-core url-rewriting .net-core middleware

是否可以将地址位置从https重写为http?我正在尝试几种方法来实现此目的,但是它总是使用https打开页面。

我试图将这些规则添加到app.Use

    app.Use(async (context, next) =>
    {
        if (context.Request.IsHttps)
        {
            if (context.Request.Path.Value.Contains("https") && !context.Request.Path.Value.Contains(".salesrater.com"))
            {
                var path = context.Request.Path.Value.Replace("https", "http");
                context.Response.Headers[HeaderNames.Location] = path;
                context.Response.Redirect(path);
            }
            else
            {
                await next();
            }
        }
    });

此案例不适用于我。然后,我尝试使用“重写”选项:

    var options = new RewriteOptions();
    options.Add(new ServerRewriteRule(cache, Configuration));
    app.UseRewriter(options);

在这样的类中实现了什么:

    var request = context.HttpContext.Request;
    var path = $"{request.Scheme}://{mapping.Domain}{request.Path.Value.Replace(mapping.Path, string.Empty)}{request.QueryString}";

    if (path.Contains("https"))
    {
        path = path.Replace("https", "http");
    }

    var response = context.HttpContext.Response;
    response.StatusCode = StatusCodes.Status302Found;
    response.Headers[HeaderNames.Location] = path;
    response.Redirect(path);
    context.Result = RuleResult.EndResponse;

更新:我忘记了在某些情况下需要过滤一些URL,这些URL应该转到https,而哪些不应该

1 个答案:

答案 0 :(得分:1)

您可以在web.config中执行此操作,而无需通过代码进行操作。使用重写规则: https://forums.iis.net/t/1206943.aspx?HTTPS+to+HTTP+redirect+in+web+config

<rule name="Redirect to HTTP" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{R:1}" pattern="^onepage/(.*)$" negate="true" />
    <add input="{HTTPS}" pattern="^ON$" />
  </conditions>
  <action type="Redirect" url="http://{HTTP_HOST}/{R:0}" redirectType="Permanent" />
</rule>