使用Querystring,Url上的RequireSSL失败

时间:2009-10-31 12:59:36

标签: asp.net-mvc ssl

我使用此代码取自MVC期货并将属性RequireSsl附加到操作。 它适用于简单的Url,如http://localhost/de/Account/Login,但如果我有一个查询字符串,则问号将被编码并且请求失败。

http://localhost/de/Account/Login?test=omg重定向到 https://localhost/de/Account/Login%3Ftest=omg。有人这个有用吗?

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RequireSslAttribute : FilterAttribute, IAuthorizationFilter
{
    public RequireSslAttribute()
    {
        Redirect = true;
    }

    public bool Redirect { get; set; }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //Validate.IsNotNull(filterContext, "filterContext");

        if (!Configuration.EnableSSL) return;

        if (!filterContext.HttpContext.Request.IsSecureConnection)
        {
            // request is not SSL-protected, so throw or redirect
            if (Redirect)
            {
                // form new URL
                UriBuilder builder = new UriBuilder
                {
                    Scheme = "https",
                    Host = filterContext.HttpContext.Request.Url.Host,
                    // use the RawUrl since it works with URL Rewriting
                    Path = filterContext.HttpContext.Request.RawUrl
                };
                filterContext.Result = new RedirectResult(builder.ToString());
            }
            else
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
            }
        }
    }


}

2 个答案:

答案 0 :(得分:1)

我改变了

 UriBuilder builder = new UriBuilder
                {
                    Scheme = "https",
                    Host = filterContext.HttpContext.Request.Url.Host,
                    // use the RawUrl since it works with URL Rewriting
                    Path = filterContext.HttpContext.Request.RawUrl
                };

                    UriBuilder builder = new UriBuilder
                {
                    Scheme = "https",
                    Host = filterContext.HttpContext.Request.Url.Host,
                    Path = filterContext.HttpContext.Request.Url.LocalPath,
                    Query = filterContext.HttpContext.Request.Url.PathAndQuery

                };

我现在不使用Url Rewriting,这就是为什么我认为这对我来说是安全的。

答案 1 :(得分:1)

UriBuilder builder = new UriBuilder
{
    Scheme = "https",
    Host = filterContext.HttpContext.Request.Url.Host,
    Path = filterContext.HttpContext.Request.Path,
    Query = filterContext.HttpContext.Request.QueryString.ToString ()
};