1.全局启用 AutoValidateAntiforgeryToken
如果需要为所有非 GET 请求自动启用防伪验证,可以在 Startup.cs 或 Program.cs 中设置:
services.AddControllersWithViews(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
这样你就不需要在每个控制器中单独声明 [AutoValidateAntiforgeryToken] 属性了。
2.在每个表单中加入
<form method="post" action="/YourAction">
@Html.AntiForgeryToken() <!--关键是这个-->
<input type="text" name="example" />
<button type="submit">提交</button>
</form>
以上方式即可应用于普通的asp.net core
3.如果使用JQuery的ajax提交表单,需要在JQuery中加入标头
$(document).ready(function () {
$('#myForm').on('submit', function (e) {
e.preventDefault(); // 阻止默认表单提交行为
const formData = $(this).serialize(); // 获取表单数据
// 获取 CSRF Token,__RequestVerificationToken是表单中添加@Html.AntiForgeryToken()后自动生成的隐藏input
const csrfToken = $('input[name="__RequestVerificationToken"]').val();
// 通过 AJAX 提交请求
$.ajax({
url: '/your-api-endpoint', // 替换为服务器端的 URL
method: 'POST',
data: formData, // 表单数据
headers: {
'RequestVerificationToken': csrfToken // 添加 CSRF Token 到请求头
},
success: function (response) {
console.log('提交成功:', response);
},
error: function (error) {
console.error('提交失败:', error);
}
});
});
});
4.为了方便,可以设置一个JQuery全局的ajax默认参数
$.ajaxSetup({
headers: {
'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
}
});
5.可以自定义隐藏的input控件name和post时header
services.AddAntiforgery(options =>
{
options.FormFieldName = "__CustomRequestVerificationToken"; // 自定义表单字段名
options.HeaderName = "X-CSRF-TOKEN"; // 自定义请求头名
});
浙公网安备 33010602011771号