Why Asp.net MVC4 can not use the cookieless of SQL Server Session state storage

半城伤御伤魂 提交于 2019-12-03 16:44:53

There's a bug in the Html.BeginForm() helper (the one that doesn't take any arguments) when used with cookieless="true". It doesn't take into account the session id when generating the url. So instead of:

<form action="/(S(kkt0zgbnuaoxad23ew33iod4))/home/index" method="post">

it generates:

<form action="/home/index" method="post">

When you post to /home/index a redirect is automatically made to /(S(kkt0zgbnuaoxad23ew33iod4)) by ASP.NET. A redirect means a GET request => your POST action will never be hit.

As a workaround you could write a custom Html.BeginForm helper to fix the bug:

public static class FormExtensions
{
    public static IDisposable MyBeginForm(this HtmlHelper htmlHelper)
    {
        var rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
        var formAction = htmlHelper.ViewContext.HttpContext.Response.ApplyAppPathModifier("~/") + rawUrl;
        var builder = new TagBuilder("form");
        builder.MergeAttributes(new RouteValueDictionary());
        builder.MergeAttribute("action", formAction);
        builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(FormMethod.Post), true);
        htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
        var form = new MvcForm(htmlHelper.ViewContext);
        return form;
    }
}

and then use:

@using (Html.MyBeginForm())
{
    ...
}

As far as the other overloads of the BeginForm helper are concerned, they should work fine and generate proper action containing the session id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!