代码之家  ›  专栏  ›  技术社区  ›  JP.

ASP.NET MVC-HTML.NET和SSL

  •  12
  • JP.  · 技术社区  · 14 年前

    在ASP.NET MVC 2中,我遇到了一个简单登录表单的问题。实际上,我的表单看起来有点像这样:

    using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm" }))
    

    我在LogOn操作方法上有一个RequiresHTTPS过滤器,但是当它执行时,我收到以下消息

    通过SSL访问

    此时唯一有效的解决方案是传入一个额外的动作htmlattribute,如下所示:

     var actionURL = "https://"  + Request.Url.Host + Request.Url.PathAndQuery;   
     using (Html.BeginForm("LogOn", "Account", new { area = "Buyers" }, FormMethod.Post, new { ID = "buyersLogOnForm", @action = actionURL }))
    

    [编辑]

    我应该说,登录下拉列表将在许多公共页上可用。我不希望我的所有网页都是HTTPS。例如,我的希望页面-任何人都可以看到-不应该是基于HTTPS的。基本上,我需要在我的表单中指定协议,但不知道如何做,或者是否可能。

    如有任何意见/建议,我将不胜感激。 提前谢谢

    3 回复  |  直到 11 年前
        1
  •  11
  •   Mathias F    14 年前

    你可以用

    <form action =" <%= Url.Action(
    "action",
    "controller",
    ViewContext.RouteData.Values,
    "https"
    ) %>" method="post" >
    
        2
  •  6
  •   Darin Dimitrov    14 年前

    [RequireHttps] 属性,该属性同时显示呈现窗体的操作和要发布到的操作。

        3
  •  5
  •   Brad J    11 年前

    我发现JP和Malcolm的混合代码示例是有效的。

    using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @action = Url.Action("Login","Account",ViewContext.RouteData.Values,"https") }))
    

    但是仍然感觉有点不舒服,所以我创建了一个自定义的BeginForm助手。自定义助手比较干净,在本地运行时不需要https。

    public static MvcForm BeginFormHttps(this HtmlHelper htmlHelper, string actionName, string controllerName)
        {
            TagBuilder form = new TagBuilder("form");
            UrlHelper Url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
    
            //convert to https when deployed
            string protocol = htmlHelper.ViewContext.HttpContext.Request.IsLocal == true? "http" : "https";
    
            string formAction = Url.Action(actionName,controllerName,htmlHelper.ViewContext.RouteData.Values,protocol);
            form.MergeAttribute("action", formAction);
    
            FormMethod method = FormMethod.Post;
            form.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
    
            htmlHelper.ViewContext.Writer.Write(form.ToString(TagRenderMode.StartTag));
    
            MvcForm mvcForm = new MvcForm(htmlHelper.ViewContext);
    
            return mvcForm;
        }
    

    用法示例:

    @using (Html.BeginFormHttps("Login", "Account"))