ASP.NET MVC - RequireHttps - 指定重定向URL

时间:2011-05-12 03:47:52

标签: asp.net asp.net-mvc ssl https

我在我的MVC2应用程序中使用[RequireHttps],但在我的测试机器中,SSL网址与实际网站网址不同(这是一个共享的SSL环境)。

实施例: 我的网站网址为http://my-domain.com,SSL网址为https://my-domain.sharedssl.com

当控制器/操作需要HTTPS时(优选在Web.config文件中),有没有办法告诉MVC重定向到该URL?

感谢。

1 个答案:

答案 0 :(得分:2)

使用内置的RequireHttpsAttribute类没有办法,但编写自己的MVC过滤器属性非常简单。像这样的东西(基于RequireHttpsAttribute类)应该起作用:

public class RedirectToHttpsAttribute : FilterAttribute, IAuthorizationFilter 
{
    protected string Host
    {
        get;
        set;
    }

    public RedirectToHttpsAttribute ( string host ) 
    {
        this.Host = host;
    }

    public virtual void OnAuthorization(AuthorizationContext filterContext) 
    {
        if (filterContext == null) {
            throw new ArgumentNullException("filterContext");
        }

        if (!filterContext.HttpContext.Request.IsSecureConnection) {
            HandleHttpsRedirect(filterContext);
        }
    }

    protected virtual void HandleHttpsRedirect(AuthorizationContext context) 
    {
        if ( context.HttpContext.Request.HttpMethod != "GET" ) 
        {
            throw new InvalidOperationException("Can only redirect GET");
        }

        string url = "https://" + this.Host + context.HttpContext.Request.RawUrl;
        context.Result = new RedirectResult(url);
    }
}

编辑:

我不确定您是否可以在FilterAttribute中读取web.config,但我想不出原因。