简体   繁体   English

Asp.net核心Razor页面-页面加载后设置变量值

[英]Asp.net core Razor Page - Setting variable value after page loads

I have a string variable named 'cookie' in my Index page model. 我的索引页面模型中有一个名为“ cookie”的字符串变量。 This cookie gets set using the following method: 使用以下方法设置此cookie:

private string GetXsrfToken()
{
    this.Request.Cookies.TryGetValue("XSRF-TOKEN", out var token);
    var xsrfToken = token ?? "TestToken";
    return xsrfToken;
}

Then in my Razor Page it is being used like this: 然后在我的Razor页面中,它的用法如下:

....
<div>
    <input type="submit" name="btn_signin" value="Sign In" id="btn_signin" formaction="~/SignIn/?_csrf=@Model.cookie" default />
</div>
....

The issue I am having is on the first time the page loads, the GetXsrfToken() method returns "TestToken". 我遇到的问题是页面首次加载时,GetXsrfToken()方法返回“ TestToken”。 After debugging I realised that this is because 'cookie' is being set before the page loads, so the XSRF-TOKEN cookie does not exist for the page yet. 调试后,我意识到这是因为在页面加载之前已设置了“ cookie”,因此该页面尚不存在XSRF-TOKEN cookie。

In the Index PageModel I have OnGet and OnPostSignIn Methods and I have tried setting the cookie variable in both using: 在Index PageModel中,我具有OnGet和OnPostSignIn方法,并且尝试使用以下两种方法来设置cookie变量:

cookie = GetXsrfToken();

HoweverThe OnGet method gets called too early, and putting it in the OnPost method means it will get called too late. 但是,OnGet方法被调用为时过早,将其放入OnPost方法中意味着它将被调用为时过晚。

So it needs to be set once the page has fully loaded, but I am unsure how to implement this. 因此,一旦页面完全加载,就需要设置它,但是我不确定如何实现这一点。 Any advice would be appreciated. 任何意见,将不胜感激。

ASP.NET Core will inject a hidden form field named __RequestVerificationToken at the end of every form with an encrypted value, and passing the same value to a cookie which is sent with the form request : ASP.NET Core将在每个带有加密值的表单的末尾注入一个名为__RequestVerificationToken的隐藏表单域,并将相同的值传递给随表单请求发送的cookie:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">

Reference : https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1 参考: https : //docs.microsoft.com/zh-cn/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1

Then you could use Jquery to get the anti-forgery token and dynamically change the button's attribute : 然后,您可以使用Jquery获取防伪令牌并动态更改按钮的属性:

@section Scripts {
  <script type="text/javascript">

    $(function () {
        var csrf = $('input[name="__RequestVerificationToken"]').val();
        $("#btn_signin").attr("formaction", "~/SignIn/?" + csrf);
        //alert(csrf);
    })
  </script>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM