ASP.NET MVC 4 cookie消失了

时间:2012-11-12 11:41:08

标签: c#-4.0 cookies asp.net-mvc-4 request-pipeline

我有一个ASP.NET应用程序,它将身份验证cookie发送到ASP.NET MVC应用程序,用作后台应用程序。

我添加了一个全局过滤器,用于检查身份验证Cookie的每个控制器操作。如果cookie存在,则允许用户进入该页面。

代码如下所示:

 public class SecurityFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            // TODO: For some reason .AUTHCookie cookie isn't exist in request context of filter,

                           HttpCookie cookie = filterContext.RequestContext.HttpContext.Request.Cookies[".AUTHCookie "];


            if (cookie != null)                 {

从另一方面,我可以在Global.asax文件的Application_BeginRequest事件中看到从ASP.NET应用程序发送的cookie。

饼干消失的地点和原因? MVC请求处理管道的哪一部分被扔掉了?

  protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            // HERE I CAN SEE BOTH cookies. In filter action only one cookie was found. The authentication cookie is thrown somewhere ...
        }  

1 个答案:

答案 0 :(得分:3)

我找到了适用于我的方案的解决方案。我在两个应用程序的机器密钥中添加了compatibilityMode =“Framework45”,它们都运行良好。

注意:如果您的某个应用程序使用旧版本的.NET框架,则必须显式配置.NET 4.5应用程序以使用早期的计算机兼容性模式,否则它们将无法加密/解密表单身份验证票。

只是为了提醒你我的情景:

WebForms ASP.NET 4.5

<machineKey compatibilityMode="Framework45" decryption="AES" validation="SHA1" decryptionKey="your_key1" validationKey="your_keu2" />
  <authentication mode="Forms">
    <forms name="_authcookie" domain=".domain.com" loginUrl="Default.aspx?View=1" defaultUrl="Default.aspx?View=1" timeout="30" path="/" protection="All" slidingExpiration="true" enableCrossAppRedirects="true" />
  </authentication>

MVC 4
<machineKey compatibilityMode="Framework45" decryption="AES" validation="SHA1" decryptionKey="your_key1" validationKey="your_keu2" />
   <authentication mode="Forms">
     <forms name="_authcookie" domain=".domain.com" defaultUrl="~/" timeout="30" path="/" protection="All" slidingExpiration="true" enableCrossAppRedirects="true" />
    </authentication>

兼容模式的可能值:

http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeysection.compatibilitymode.aspx