.net core ValidateAntiForgeryToken特性 阻止跨站点请求伪造(CSRF) 示例

1 后台控制器

        [ValidateAntiForgeryToken]
        public IActionResult AcceptList([FromForm]string reqId, [FromForm] List<RequestModel> requestModel)
        {
            return Json(new { code = 0, msg = "操作成功2" });
        }

2 前端代码

添加     @Html.AntiForgeryToken()

<div>
    <!--这段代码会生成如下元素
    <input name="__RequestVerificationToken" type="hidden" value="CfDJ8Iq1FkUsGUVDjXSXvr3mD_aBj_NbQuayfjr5Kp-DB_wgGvNNqR8aedZeHMIEcgfwSV4xqNxYjvxRlu_QX4oF2jXpSLlJ-m50T02iUPBeUKD6o7A1pV9VW68z6A7iPw_zYaCXmDqKCL4GTLIoheZD29E" />
    -->
    @Html.AntiForgeryToken()
</div>

ajax 请求代码

     //获取防伪标记
    var token = $([name=__RequestVerificationToken]).val();
    // 后台接收 list
    $.ajax({
        type: post,
        url: /Test/AcceptList,
        data: { __RequestVerificationToken: token,reqId: id, requestModel: [{ Id: 2, name: id2, money: 22, CreateTime: new Date(2021-05-29 22:53:10) }, { Id: 1, name: id1, money: 11, CreateTime: new Date(2021-05-29 12:53:10) }] },
        contentType: application/x-www-form-urlencoded,
        dataType: json,
        success: function (res) {
            if (res.code == 0)
                alert(res.msg);
        },
        error: function () {
        },
        beforeSend: function () {
        },
        complete: function () {
        }
    });

 

.net core ValidateAntiForgeryToken特性 阻止跨站点请求伪造(CSRF) 示例

上一篇:js监听网页窗口大小,拖动网页边框缩小或放大,网页里的长度会随着网页边框大小改变


下一篇:从零开始学VUE之Webpack(依赖环境NodeJs安装)