如何在Cookie __RequestVerificationToken_Lw__上设置属性samesite的值

时间:2019-06-17 15:46:26

标签: html token antiforgerytoken samesite

我在cshtml页面上有一个antirforgery令牌(@ Html.AntiForgeryToken()),该页面会生成一个cookie RequestVerificationToken_Lw 。此Cookie上的属性值为HTTP和Secure。但是我还需要设置SameSite。我该如何实现?

@Html.AntiForgeryToken()

__RequestVerificationToken_Lw__

1 个答案:

答案 0 :(得分:4)

可以帮忙吗?

在Global.asax.cs

 public class MvcApplication : System.Web.HttpApplication
 {

        protected void Application_PreSendRequestHeaders(object sender,EventArgs e) {
            // This code will mark the __RequestVerificationToken cookie SameSite=Strict 
            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);
                    }
                }
            }           
        }
 }