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

相關文章
相關標籤/搜索