必填的防伪表单字段“__RequestVerificationToken"不存在.AngularJS MVC [英] The required anti-forgery form field "__RequestVerificationToken" is not present. AngularJs MVC

查看:37
本文介绍了必填的防伪表单字段“__RequestVerificationToken"不存在.AngularJS MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 AngularJs 将 RequestVerificationToken 从网页传递到服务器.

我的 AngularJs 代码是:

var app = angular.module('validation', []);app.controller('SignUpController', function ($scope, $http) {$scope.model = {};$scope.email = {};$scope.sendEmail = 函数 () {$http({方法:'POST',url: '/联系方式/测试',数据:$scope.email,标题:{'RequestVerificationToken': $scope.antiForgeryToken}}).成功();};});

自定义属性代码:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]公共类 CustomAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter{私有无效 ValidateRequestHeader(HttpRequestBase 请求){字符串 cookieToken = String.Empty;字符串 formToken = String.Empty;string tokenValue = request.Headers["RequestVerificationToken"];if (!String.IsNullOrEmpty(tokenValue)){string[] tokens = tokenValue.Split(':');if (tokens.Length == 2){cookieToken = tokens[0].Trim();formToken = tokens[1].Trim();}}AntiForgery.Validate(cookieToken, formToken);}public void OnAuthorization(AuthorizationContext filterContext){尝试{如果 (filterContext.HttpContext.Request.IsAjaxRequest()){ValidateRequestHeader(filterContext.HttpContext.Request);}别的{AntiForgery.Validate();}}catch (HttpAntiForgeryException e){throw new HttpAntiForgeryException("未找到防伪令牌cookie");}}}

形式是:

@functions{公共字符串 GetAntiForgeryToken(){字符串 cookieToken, formToken;AntiForgery.GetTokens(null, out cookieToken, out formToken);返回 cookieToken + ":" + formToken;}}<div ng-app="验证" ng-controller="SignUpController"><form role="form" id="frmContact" action="@Url.Action("Index", "Contact")" method="POST"><input id="antiForgeryToken" ng-model="antiForgeryToken" type="hidden" ng-init="antiForgeryToken='@GetAntiForgeryToken()'"/><fieldset class="form-group">@Html.LabelFor(x => x.EmailTitle)@Html.TextBoxFor(x => x.EmailTitle, new { placeholder = @Resource.EmailTitle, @class = "form-control", data_ng_model = "new.email.title" })</fieldset><fieldset class="form-group">@Html.LabelFor(x => x.EmailAddress)@Html.TextBoxFor(x => x.EmailAddress, new { placeholder = @Resource.EmailAddress, @class = "form-control", data_ng_model = "new.email.address" })</fieldset><fieldset class="form-group">@Html.LabelFor(x => x.EmailMessage)@Html.TextAreaFor(x => x.EmailMessage, new { placeholder = @Resource.EmailMessage, @class = "form-control", data_ng_model = "new.email.message" })</fieldset><div><button type="submit" name="btnEmailForm" id="btnEmailForm" class="btnLogin" ng-click="sendEmail()" value="sendMessage">@Resource.ContactFormSendMessageButton</button>

<div id="errorMessages" class="error">{{message}}</div></表单>

我已阅读以下帖子,但似乎无法解决问题,并且还从 https://github.com/techbrij/angularjs-asp-net-mvc 在该示例中有效,但在我的 MVC 应用程序中无效:

http://techbrij.com/angularjs-antiforgerytoken-asp-net-mvc

https://parthivpandya.wordpress.com/2013/11/25/angularjs-and-antiforgerytoken-in-asp-net-mvc/

AngularJS Web Api AntiForgeryToken CSRF

http://bartwullems.blogspot.co.uk/2014/10/angularjs-and-aspnet-mvc-isajaxrequest.html

antiforgeryToken 的确切放置位置

http://www.ojdevelops.com/2016/01/using-antiforgerytokens-in-aspnet-mvc.html

谁能帮忙解决这个问题

解决方案

在这种情况下,您执行表单 submit$scope.sendEmail 操作,它们可能会与另一个,为了防止这种行为,您可以使用 ng-submit 指令.并添加属性:name='__RequestVerificationToken'ng-value="antiForgeryToken" 到相应的 input.

I'm unable to pass the RequestVerificationToken from webpage to server using AngularJs.

My AngularJs Code is:

var app = angular.module('validation', []);
app.controller('SignUpController', function ($scope, $http) {
    $scope.model = {};
    $scope.email = {};
    $scope.sendEmail = function () {
        $http({
            method: 'POST',
            url: '/Contact/Test',
            data: $scope.email,
            headers: {
                'RequestVerificationToken': $scope.antiForgeryToken
            }
        }).success();
    };
});

Custom Attribute Code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {


        private void ValidateRequestHeader(HttpRequestBase request)
        {
            string cookieToken = String.Empty;
            string formToken = String.Empty;
            string tokenValue = request.Headers["RequestVerificationToken"];
            if (!String.IsNullOrEmpty(tokenValue))
            {
                string[] tokens = tokenValue.Split(':');
                if (tokens.Length == 2)
                {
                    cookieToken = tokens[0].Trim();
                    formToken = tokens[1].Trim();
                }
            }
            AntiForgery.Validate(cookieToken, formToken);
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {

            try
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    ValidateRequestHeader(filterContext.HttpContext.Request);
                }
                else
                {
                    AntiForgery.Validate();
                }
            }
            catch (HttpAntiForgeryException e)
            {
                throw new HttpAntiForgeryException("Anti forgery token cookie not found");
            }
        }
    }

Form is:

@functions{
    public string GetAntiForgeryToken()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;
    }
}
<div ng-app="validation" ng-controller="SignUpController">
    <form role="form" id="frmContact" action="@Url.Action("Index", "Contact")" method="POST">
        <input id="antiForgeryToken" ng-model="antiForgeryToken" type="hidden" ng-init="antiForgeryToken='@GetAntiForgeryToken()'" />
        <fieldset class="form-group">
            @Html.LabelFor(x => x.EmailTitle)
            @Html.TextBoxFor(x => x.EmailTitle, new { placeholder = @Resource.EmailTitle, @class = "form-control", data_ng_model = "new.email.title" })
        </fieldset>
        <fieldset class="form-group">
            @Html.LabelFor(x => x.EmailAddress)
            @Html.TextBoxFor(x => x.EmailAddress, new { placeholder = @Resource.EmailAddress, @class = "form-control", data_ng_model = "new.email.address" })
        </fieldset>
        <fieldset class="form-group">
            @Html.LabelFor(x => x.EmailMessage)
            @Html.TextAreaFor(x => x.EmailMessage, new { placeholder = @Resource.EmailMessage, @class = "form-control", data_ng_model = "new.email.message" })
        </fieldset>


        <div>
            <button type="submit" name="btnEmailForm" id="btnEmailForm" class="btnLogin" ng-click="sendEmail()" value="sendMessage">@Resource.ContactFormSendMessageButton</button>
        </div>
        <div id="errorMessages" class="error">{{message}}</div>
    </form>
</div>

I have read the following posts, but cannot seem to solve the problem, and also took code from https://github.com/techbrij/angularjs-asp-net-mvc which works in that example but not in my MVC application:

http://techbrij.com/angularjs-antiforgerytoken-asp-net-mvc

https://parthivpandya.wordpress.com/2013/11/25/angularjs-and-antiforgerytoken-in-asp-net-mvc/

AngularJS Web Api AntiForgeryToken CSRF

http://bartwullems.blogspot.co.uk/2014/10/angularjs-and-aspnet-mvc-isajaxrequest.html

Where exactly to put the antiforgeryToken

http://www.ojdevelops.com/2016/01/using-antiforgerytokens-in-aspnet-mvc.html

Can anyone help with this problem

解决方案

At this case you perform form submit and $scope.sendEmail operations and they may conflict one with another, to prevent this behavior you can use ng-submit directive. And also add attributes: name= '__RequestVerificationToken' and ng-value="antiForgeryToken" to corresponding input.

这篇关于必填的防伪表单字段“__RequestVerificationToken"不存在.AngularJS MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆