本文介绍了使用 ASP.NET MVC 应用重定向远离 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 ASP.NET MVC 2 并且有一个通过 HTTPS 保护的登录页面.为确保用户始终通过 SSL 访问这些页面,我向控制器添加了属性 [RequireHttps].这可以完美地完成工作.

I'm using ASP.NET MVC 2 and have a login page that is secured via HTTPS. To ensure that the user always accesses those pages via SSL, I've added the attribute [RequireHttps] to the controller. This does the job perfectly.

当他们成功登录后,我想将他们重定向回 HTTP 版本.但是,没有 [RequireHttp] 属性,我正在努力思考如何实现这一点.

When they have successfully logged in, I'd like to redirect them back to HTTP version. However, there isn't a [RequireHttp] attribute and I'm struggling to get my head around how I might achieve this.

增加的(潜在)复杂性是网站在生产时托管在域的路径上,但出于开发和测试目的,它位于子目录/虚拟目录/应用程序中.

The added (potential) complication is that the website when in production is hosted at the route of the domain, but for development and testing purposes it is within a sub directory / virtual directory / application.

我是不是想得太多了,是否有一个简单的解决方案让我眼前一亮?还是稍微复杂一点?

Am I over-thinking this and is there an easy solution staring me in the face? Or is it a little more complex?

推荐答案

经过一番挖掘,我沿着自己的路线滚动,因为似乎没有一个好的内置解决方案(如提到,MVC2 应用程序有一个很好的 [RequireHttps]).受到 çağdaş这个问题 并且我改编了以下代码:

After a bit of digging, I went along the lines of rolling my own as there didn't appear to be a good built-in solution to this (as mentioned, there is a great one for MVC2 applications in the form of [RequireHttps]). Inspired by çağdaş's solution to this problem and I adapated to come up with the following code:

public class RequireHttp : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // If the request has arrived via HTTPS...
        if (filterContext.HttpContext.Request.IsSecureConnection)
        {
            filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.ToString().Replace("https:", "http:")); // Go on, bugger off "s"!
            filterContext.Result.ExecuteResult(filterContext);
        }
        base.OnActionExecuting(filterContext);
    }
}

我现在可以将它添加到我的控制器方法中,它的行为(看起来)如预期的那样.如果我从 HTTPS 协议重定向到控制器上的 Index 操作,它将重定向到 HTTP.它只允许 HTTP 访问索引 ActionResult.

I can now add this to my Controller methods and it behaves (seemingly) as expected. If I redirect to the Index action on my controller from a HTTPS protocol, it will redirect to HTTP. It only allows HTTP access to the Index ActionResult.

[RequireHttp]
public ActionResult Index() {
    return View();
}

这篇关于使用 ASP.NET MVC 应用重定向远离 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:32