ASP.NET MVC 3中Ajax POST携带AntiForgeryToken报500内部服务器错误
ASP.NET MVC3 Ajax 结合 AntiForgeryToken 500错误解决办法
问题根源
你的代码核心问题是Ajax请求的数据格式错误,手动拼接的字符串不符合application/x-www-form-urlencoded编码规范,导致服务器无法正确解析__RequestVerificationToken参数,触发AntiForgeryToken验证失败,返回500内部错误。
修正步骤
1. 修复JavaScript的Ajax数据传递方式
放弃手动拼接字符串,改用对象形式传递数据,jQuery会自动处理编码和格式:
$("#headerNext").click(function () { var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ type: "POST", url: "/Survey/LinkedSurveyAsJson", // 用对象传递参数,自动完成编码 data: { __RequestVerificationToken: token, id: '@Model.CustomerSurveyId', lang: '@(Model.Language == "ar" ? "ar" : "en")' }, contentType: 'application/x-www-form-urlencoded; charset=utf-8', success: function (response) { if (response) { var data = $.parseJSON(response); $('#SurveyQuestions').html(templateQuestion(data)); console.log(data); $('#headerText').hide(); $('#headerNext').hide(); $('#next').show(); } }, error: function (xhr) { // 修正错误信息获取逻辑 showErrorMessage(xhr.responseText || xhr.statusText); document.getElementById(bid).disabled = false; } }); });
2. 简化HTML表单(可选但推荐)
表单无文件上传需求,不需要enctype="multipart/form-data",去掉后避免不必要的解析开销:
@using (Html.BeginForm("Index", "Survey", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" })) { @Html.AntiForgeryToken() }
3. 确保参数类型匹配
Action中的id是Guid?类型,要保证@Model.CustomerSurveyId输出的是有效的Guid字符串(无多余引号),否则服务器无法将字符串转换为Guid,也会引发500错误。
额外说明
- MVC的AntiForgeryToken验证要求**表单参数
__RequestVerificationToken和Cookie中的__RequestVerificationToken**同时存在且匹配,Ajax请求默认会自动携带Cookie,只需保证表单参数传递正确即可。 - 若后续需使用
application/jsoncontentType传递数据,需将参数封装为ViewModel类,同时确保请求中正确传递token且Cookie正常携带。
内容的提问来源于stack exchange,提问作者Warda
相关产品推荐
相关产品推荐

