재우니의 블로그


asp.net mvc 의 form 태그를 자동적으로 AntiForgeryToken 사용하도록 하기 위해 핼퍼를 만든 부분임

// BeginForm replacement for HtmlHelper
public static MvcForm BeginSecureForm
(this HtmlHelper htmlHelper, string actionName, string controllerName)
{
    var form = htmlHelper.BeginForm(actionName, controllerName);
    htmlHelper.ViewContext.Writer.Write(htmlHelper.AntiForgeryToken().ToHtmlString());
    return form;
}

// BeginForm replacement for AjaxHelper
public static MvcForm BeginSecureForm(this AjaxHelper ajaxHelper, AjaxOptions ajaxOptions)
{
    var form = ajaxHelper.BeginForm(ajaxOptions);
    ajaxHelper.ViewContext.Writer.Write(AntiForgery.GetHtml());
    return form;
}


사용법

// View
@using (Html.BeginSecureForm("AddUser", "Home"))
{
    @Html.TextBox("userName")
    <button type="submit">Save</button>
}


https://www.codeproject.com/Tips/1170283/Validate-Anti-Forgery-in-ASP-NET-MVC-The-Automated