MVC Controller Button 添加自定义的Form防伪认证

问题参考:https://stackoverflow.com/questions/29009650/c-sharp-antiforgerytoken-attribute-causes-stackoverflowexception-in-mvc-applicat

系统默认的Form防伪认证为submit按钮,如果通过button按钮,可很方便的通过AJAX进行Json数据的传递。

可以比较有效地防止恶意刷新。

HTML:

 <form class="control-group">

                                        @Html.AntiForgeryToken

                                        <button type="button" class="btn blue" id="btn_searchCNKI"><i class="icon-ok"></i> 查询</button>

                                    </form>

JavaScript:

var token = $('input[name=__RequestVerificationToken]').val();
        var headers = {};
        //防伪标记放入headers            
        headers["__RequestVerificationToken"] = token;
        $.ajax({
            url: '/xxxxx/xxxxx',
            data: {"ID": ID},
            headers: headers,
            //data: _list,  
            dataType: "json",
            type: "POST",
            traditional: true,
            success: function (response) {}

Controller:

 '自定义的Ajax Post的服务器防伪验证
        'https://stackoverflow.com/questions/29009650/c-sharp-antiforgerytoken-attribute-causes-stackoverflowexception-in-mvc-applicat
        Public Class MyValidateAntiForgeryToken
            Inherits AuthorizeAttribute
            Public Overrides Sub OnAuthorization(ByVal filterContext As AuthorizationContext)
                Dim request = filterContext.HttpContext.Request
                If request.HttpMethod = Net.WebRequestMethods.Http.Post Then
                    If request.IsAjaxRequest() Then
                        Dim antiForgeryCookie = request.Cookies(Helpers.AntiForgeryConfig.CookieName)
                        Dim cookieValue = If(antiForgeryCookie IsNot Nothing, antiForgeryCookie.Value, Nothing)
                        Try
                            Helpers.AntiForgery.Validate(cookieValue, request.Headers("__RequestVerificationToken"))
                        Catch ex As Exception

                        End Try
                    Else
                        MyBase.OnAuthorization(filterContext)
                    End If
                End If
            End Sub
        End Class
 <MyValidateAntiForgeryToken>
        <HttpPost>
        Function myDoSomething(inJson As inJson) As JsonResult
            'do something
            return json(outjson, JsonRequestBehavior.AllowGet)
        End Function

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值