Razor Page in AJAX

1. Since Razor Pages comes provide security token / authentication, to prevent cross-site request forgery (referred XSRF or CSRF), so the API framework and MVC use of slightly different.

2. So when we use the form Razor Pages in the form submitted data, the framework will automatically help us generate a hidden Input, and join in the request packet header when we submit the form.

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8P-uB18ojyNBnPHyBPpQMcjMi3bb01uB9VeJk0C6GO2bVdSnt7aSGr63GOKObkLt7HBZqhVPvlmS9GLn8-To2XHw5F1L3ARqXFsXQhqpMSnuVSRBpYkZo6-7Gtv3CJrUTR6uRZdEh5ZwKsLpZSqdZEs" />

3. However, when we use AJAX to submit data to a post method, you will find the server return a 400 status code, it is because we do not carry in the request header token in the past, so we should write

 @ Html.AntiForgeryToken () // generate html page on the hidden input, token stored on the inside, of course, if there is a form form on your page will not have to write this

 

 $.ajax({
                    method: 'post',
                    url: "/?handler=Data",
                    headers: {
                        RequestVerificationToken:
                            $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    success: function (data) {
                            console.log(data);
                        }, error: function (error) {
                            console.log(error);
                        }
                    })

 

Guess you like

Origin www.cnblogs.com/ROOKIEDEBUG/p/10985083.html