【发布时间】:2018-11-08 17:19:59
【问题描述】:
是否可以将地址位置从 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,哪些不应该
【问题讨论】:
-
在第一种情况下你告诉它
context.Response.Redirect(context.Request.Path.Value);,当然它会回到 HTTPS :) 你还需要使用完整的 URI,路径不包含方案 (HTTPS) . -
@juunas,是的,没有注意到这一点,只是更新了这篇文章,也对我不起作用,它仍然使用 https 运行网站,而不是重定向到 http :(
标签: c# asp.net-core url-rewriting .net-core middleware