【问题标题】:How to set sameSite=None in Asp.Net MVC generated cookies?如何在 Asp.Net MVC 生成的 cookie 中设置 sameSite=None?
【发布时间】:2020-08-17 11:01:32
【问题描述】:

我有一个 asp.net MVC 应用程序,我想为该应用程序设置所有 cookie sameSite=None。我在 web.config 中设置了以下几行,但应用程序设置了没有 SameSite=None 的 cookie。 我在 web.config 中添加了以下两个配置。请参阅下面的屏幕截图,其中同时放置了 .AspNet.ApplicationCookie__RequestVerificationToken cookie,但未使用 sameSite=None。请帮忙。

<system.web>
        <httpCookies requireSSL="true"/>
        <sessionState cookieSameSite="None"/>
</system.web>

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我是从代码中完成的,它有效
    在 global.asax.cs 中:

     public class MvcApplication : HttpApplication
                    {
                    
                       protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
                       {
            .....
                            if (Request.Cookies.Count > 0)
                            {                        
                                foreach (string s in Request.Cookies.AllKeys)
                                {
                                    HttpCookie c = Request.Cookies[s];
                                    c.SameSite = System.Web.SameSiteMode.None;
                                    Response.Cookies.Set(c);
                                }
                           }
            ....
                        }
                    }
    

    如果你想要特定的 cookie

     if (Request.Cookies.Count > 0)
                {
                    foreach (string s in Request.Cookies.AllKeys)
                    {
                        if (s.ToLower() == "__requestverificationtoken")
                        {
                            HttpCookie c = Request.Cookies[s];
                            c.SameSite = System.Web.SameSiteMode.Strict;
                            Response.Cookies.Set(c);
                        }
                    }
                }
    

    【讨论】:

    • 非常感谢!我与这个问题斗争了很长时间。我尝试过的所有 Microsoft 解决方案都不起作用。这很简单,很有意义,最重要的是,它有效。我正在使用 MVC .NET 4.7.2,您的解决方案救了我。再次,谢谢你!!!
    猜你喜欢
    • 2021-07-22
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2020-05-17
    • 2019-12-18
    • 2020-05-01
    相关资源
    最近更新 更多