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

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

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

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

HTML:

 
@Html.AntiForgeryToken

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
 
        
        Function myDoSomething(inJson As inJson) As JsonResult
            'do something
            return json(outjson, JsonRequestBehavior.AllowGet)
        End Function

 

你可能感兴趣的:(MVC Controller Button 添加自定义的Form防伪认证)