ASP.NET MVC Validation of ViewState MAC failed

前端 未结 3 694
星月不相逢
星月不相逢 2020-12-13 02:46

After publishing a new build of my ASP.NET MVC web application, I often see this exception thrown when browsing to the site:

System.Web.Mvc.HttpAntiForgeryException:

相关标签:
3条回答
  • 2020-12-13 03:13

    Under the covers, the MVC AntiForgeryToken attribute uses the machinekey for encryption. If you don't specify a machinekey in the web.config (see here), one is automatically generated for you by ASP.NET (full description).

    If the ASP.NET application is restarted (e.g. do an iisreset), the AntiForgeryToken within the browser cookie will still be encrypted with an old machine key, hence why it crashes with the above error.

    So you should always specify a machinekey in your web.config when using MVC, e.g.

    <configuration>
        <system.web>
            <machineKey  
                validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"           
                decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
                validation="SHA1"
                decryption="AES"
            />
        ...
    
    0 讨论(0)
  • 2020-12-13 03:15

    If you're on a server farm, make sure your machine key on every server is the same.

    0 讨论(0)
  • 2020-12-13 03:23

    I too had this problem, and expecting the users to clear their cache, cookies or refreshing the page isn't acceptable.

    Adding a machinekey to web.config is will fix this. I used this tool to quickly generate a key so I don't see these errors in development and then I generate one properly when the site goes into production.

    http://aspnetresources.com/tools/machineKey

    0 讨论(0)
提交回复
热议问题