MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交

1、在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击。

2、相应的我们要在Controller中也要加入[ValidateAntiForgeryToken]过滤特性。该特性表示检测服务器请求是否被篡改。注意:该特性只能用于post请求,get请求无效。

3、至于JS,我们的项目中引用的是<script src="@Url.Content("~/Content/js/jqueryToken-1.4.2.js")" type="text/JavaScript"></script>

在JS时要使用: $.ajaxAntiForgery才行,
如:
 $.ajaxAntiForgery({
            type: "post",
            data: { GroupName: $("#GroupName").val(), GroupPhones: $("#GroupPhones").val() },
            dataType: "json",
            url: "/Event/Mass/AddGroup",
            success: function (data) {
                if (data) {

                    alert("添加成功 ");
                    $.unblockUI();
                }
                else {
                    alert("添加失败 ");
                }
         }
 })

注:对数据进行增删改时要防止csrf攻击!

另外一种方式

 

复制代码
复制代码
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}
复制代码
复制代码

 

复制代码
复制代码
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="myDiv" data-url="@Url.Action("Index", "Home")">
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute
</div>

<script type="text/javascript">
    $('#myDiv').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                someValue: 'some value' 
            },
            success: function (result) {
                alert(result.someValue);
            }
        });
        return false;
    });
</script>
复制代码
复制代码

posted on   大西瓜3721  阅读(251)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2015-10-14 C# String.Format大全
2015-10-14 epub3 in action: epub3文件格式简介

导航

点击右上角即可分享
微信分享提示