How can I supply an AntiForgeryToken when posting JSON data using $.ajax?
How can I supply an AntiForgeryToken when posting JSON data using $.ajax?
回答1
You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link.
- Put the token in the headers.
- Create a filter.
- Put the attribute on your method.
Here is my solution:
var token = $('input[name="__RequestVerificationToken"]').val(); var headers = {}; headers['__RequestVerificationToken'] = token; $.ajax({ type: 'POST', url: '/MyTestMethod', contentType: 'application/json; charset=utf-8', headers: headers, data: JSON.stringify({ Test: 'test' }), dataType: "json", success: function () {}, error: function (xhr) {} });
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var httpContext = filterContext.HttpContext; var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName]; AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]); } } [HttpPost] [AllowAnonymous] [ValidateJsonAntiForgeryToken] public async Task<JsonResult> MyTestMethod(string Test) { return Json(true); }
回答2
What is wrong is that the controller action that is supposed to handle this request and which is marked with the [ValidateAntiForgeryToken]
expects a parameter called __RequestVerificationToken
to be POSTed along with the request.
There's no such parameter POSTed as you are using JSON.stringify(data)
which converts your form to its JSON representation and so the exception is thrown.
So I can see two possible solutions here:
Number 1: Use x-www-form-urlencoded
instead of JSON
for sending your request parameters:
data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val(); data["fiscalyear"] = fiscalyear; // ... other data if necessary $.ajax({ url: url, type: 'POST', context: document.body, data: data, success: function() { refresh(); } });
Number 2: Separate the request into two parameters:
data["fiscalyear"] = fiscalyear; // ... other data if necessary var token = $('[name=__RequestVerificationToken]').val(); $.ajax({ url: url, type: 'POST', context: document.body, data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) }, success: function() { refresh(); } });
So in all cases you need to POST the __RequestVerificationToken
value.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-09-22 使用entityframework操作sqlite数据库
2016-09-22 excel在一个图表内,显示折线图和柱状图
2016-09-22 通过NuGet获取sqlite对应的.net的dll
2015-09-22 comparison of floating point numbers with equality operator. possible loss of precision while rounding values
2015-09-22 Formatting is Specified but argument is not IFormattable
2015-09-22 Covariance and Contravariance in C#的搜索条件
2015-09-22 Covariance and Contravariance in C#, Part Two: Array Covariance