asp.net-mvc – 在ASP.NET MVC中在HTTP和HTTPS之间移动

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 在ASP.NET MVC中在HTTP和HTTPS之间移动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我找到了[RequiresHttps]属性,但是一旦你在https中你的那种卡在那里,那么试着能够对一个网址(和方案)进行操作我发现我最终不得不创建我自己的ExtendedController为不使用[RequireHttps]的操作恢复为http.

只是想知道我在做什么是好的还是有更好的方法

public class ExtendedController : Controller
{
    protected virtual void HandleHttpRequest(AuthorizationContext filterContext)
    {
        if (!string.Equals(filterContext.HttpContext.Request.HttpMethod,"GET",StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("Cannot post between https and http.");
        }
        string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
        filterContext.Result = new RedirectResult(url);
    }

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
        if (!attributes.Any(a => a is RequireHttpsAttribute))
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (filterContext.HttpContext.Request.IsSecureConnection)
            {
                this.HandleHttpRequest(filterContext);
            }
        }
    }
}

解决方法

你所拥有的是语法上正确的,但建议是创建一个新的Action过滤器,它继承自默认的RequireHttpsAttribute,并使用一个参数在http和https之间切换.
public class RequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
{
    public bool RequireSecure = false;

    public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)

    {
        if (RequireSecure)
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            // non secure requested
            if (filterContext.HttpContext.Request.IsSecureConnection)
            {
                HandleNonHttpRequest(filterContext);
            }
        }
    }

    protected virtual void HandleNonHttpRequest(AuthorizationContext filterContext)
    {
        if (String.Equals(filterContext.HttpContext.Request.HttpMethod,StringComparison.OrdinalIgnoreCase))
        {
            // redirect to HTTP version of page
            string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(url);
        }
    } 
}

然后,在您的操作方法或控制器上,您将使用:

[RequireHttps (RequireSecure = true)]

要么

[RequireHttps (RequireSecure = false)]
原文链接:https://www.f2er.com/aspnet/248769.html

猜你在找的asp.Net相关文章