Nhóm :
Admin
Tham gia:
15-04-2010
Bài viết:
13
Lần thăm:
93

Fix: AntiForgeryToken MVC Validation of viewstate MAC failed

Khi các bạn triển khai MVC gặp lỗi này khi gen form có sử dụng AntiForgeryToken

Mặc dù config
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />

Hay:

<machineKey .../>

cũng không có hiệu quả


Chia sẻ với các bạn cách khắc phục lỗi này:


   public static class AntiForgeryExtensions
    {

        // Methods
        public static MvcHtmlString AntiForgeryTokenX(this HtmlHelper helper)
        {
            return AntiForgeryTokenX(helper, null);
        }

        public static MvcHtmlString AntiForgeryTokenX(this HtmlHelper helper, string salt)
        {
            MvcHtmlString _fragment;
            string path = helper.ViewContext.HttpContext.Request.ApplicationPath;
            try
            {
                _fragment = helper.AntiForgeryToken(salt, null, path);
            }
            catch (HttpAntiForgeryException)
            {
                // okay, scrub the cookie and have another go.
                string _cookieName = GetAntiForgeryTokenName(path);
                helper.ViewContext.HttpContext.Request.Cookies.Remove(_cookieName);
                _fragment = helper.AntiForgeryToken(salt, null, path);
            }
            return _fragment;
        }

        #region AntiForgeryData code that shouldn't be sealed
        // Copied from AntiForgeryData since they aren't accessible.
        internal static string GetAntiForgeryTokenName(string appPath)
        {
            if (String.IsNullOrEmpty(appPath))
            {
                return "__RequestVerificationToken";
            }
            else
            {
                return "__RequestVerificationToken_" + Base64EncodeForCookieName(appPath);
            }
        }
        private static string Base64EncodeForCookieName(string s)
        {
            byte[] _rawBytes = Encoding.UTF8.GetBytes(s);
            string _base64String = Convert.ToBase64String(_rawBytes);

            // replace base64-specific characters with characters that are safe for a cookie name
            return _base64String.Replace('+', '.').Replace('/', '-').Replace('=', '_');
        }
        #endregion

    }


Cách dùng như cũng không có gì khác : <%=Html.AntiForgeryTokenX("SALT") %>

Chúc bạn thành công!