Razor Page 处理Ajax Post 400问题

为了防止CSRF攻击,新版本的框架增强作了相关处理

PageModel上加入[ValidateAntiForgeryToken]

[ValidateAntiForgeryToken]
    public class LoginModel : PageModel

Html里生成token

<el-form style="max-width:600px; margin:20px auto;"  method="post">
            @Html.AntiForgeryToken()

全局设置Ajax提交token

$.ajaxSetup({
        beforeSend: function (xhr) {
             xhr.setRequestHeader("RequestVerificationToken", $('input:hidden[name="__RequestVerificationToken"]').val());
        }
    })

禁用上述设置

(有时候这种安全性是没必要须的,好比不是在页面里发起请求,须要采用其它安全机制)html

//在     public void ConfigureServices(IServiceCollection services) 方法里:
            services.AddMvc()
                .AddRazorPagesOptions(o => { o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); })
                .InitializeTagHelper<FormTagHelper>((helper, context) => helper.Antiforgery = false)
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

参照:https://www.cnblogs.com/tdfblog/p/disable-antiforgery-token-validation-in-asp-net-core-razor-page.htmlajax

相关文章
相关标签/搜索