gpt4 book ai didi

asp.net-mvc - 在 ASP.NET MVC 中使用 SSL 操作过滤器重定向循环

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:58 24 4
gpt4 key购买 nike

我正在使用 ActionFilter(见下文)来检测 1. 当前 Controller /操作是否需要 SSL 和 2. 当前正在使用 SSL,并相应地重定向。

这在本地工作正常(在 IIS 7 中使用虚拟证书),但是一旦我在服务器上启动它,我就会收到一个错误,指示无限重定向循环。

有什么想法吗?

 public class SslFilter : ActionFilterAttribute
{
public SslFilter(bool sslRequired)
{
SslRequired = sslRequired;
}

public bool SslRequired { get; set; }


public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;

var builder = new UriBuilder(req.Url);

if (SslRequired && !req.IsSecureConnection)
{
builder.Scheme = Uri.UriSchemeHttps;
builder.Port = 443;
res.Redirect(builder.Uri.ToString());

}
else if (!SslRequired && req.IsSecureConnection)
{
builder.Scheme = Uri.UriSchemeHttp;
builder.Port = 80;
res.Redirect(builder.Uri.ToString());
}

base.OnActionExecuting(filterContext);
}
}

Firefox 错误:

The page isn't redirecting properly

Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

This problem can sometimes be caused by disabling or refusing to accept cookies.

最佳答案

尝试以更 MVCish 的方式重定向:

var builder = new UriBuilder(req.Url);

if (SslRequired && !req.IsSecureConnection)
{
builder.Scheme = Uri.UriSchemeHttps;
builder.Port = 443;
filterContext.Result = new RedirectResult(builder.Uri.ToString());
filterContext.Cancel = true;
}
else if (!SslRequired && req.IsSecureConnection)
{
builder.Scheme = Uri.UriSchemeHttp;
builder.Port = 80;
filterContext.Result = new RedirectResult(builder.Uri.ToString());
filterContext.Cancel = true;
}
else
{
base.OnActionExecuting(filterContext);
}

关于asp.net-mvc - 在 ASP.NET MVC 中使用 SSL 操作过滤器重定向循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2323544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com