后端使用.net mvc开发,前端使用axios发送post请求遇到错误:所需的防伪表单字段“__RequestVerificationToken”不存在。

看到此提示我们知道原因是:MVC的跨站攻击(CSRF)安全机制获取不到__RequestVerificationToken。但是不知道axios如何传参才能让后端的安全机制获取到,百度各种搜索半天后扔未果,后来想办法 google,秒获答案 (谷歌真不是吹的,牛!!),虽然不是正面解决,但解决方案依然很满意 、很优秀,解决方法如下:

1、新建一个过滤器

    /// <summary>
    /// axios不能通过跨站验证,因此自定义验证方法,action方法上要标记此过滤器名称
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public sealed class ValidateAntiForgeryToken2Attribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("fail");
            }
            var httpContext = filterContext.HttpContext;
            //AntiForgeryConfig.CookieName 默认等于__RequestVerificationToken
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
        }
    }

2、Action方法上 之前使用默认的过滤器“ValidateAntiForgeryToken”,现在换成我们自定义的:“ValidateAntiForgeryToken2”

3、前端axios发送请求时在headers中写入“__RequestVerificationToken” 这是默认名称,如果您自定义了名称请换成自定义的名称 ,在axios全局配置中写入__RequestVerificationToken:

axios.create({
    headers: {
        "__RequestVerificationToken": document.querySelector("input[name=__RequestVerificationToken]").value,
    },
});

完!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐