【问题标题】:AntiForgeryToken With Jquery Ajax Calls Using ViewModels?AntiForgeryToken 与使用 ViewModels 的 Jquery Ajax 调用?
【发布时间】:2012-06-01 14:11:44
【问题描述】:

我已阅读此处关于让 AntiForgeryToken 与 Jquery ajax reuests 一起使用的信息,我基本上必须确保我使用类似的东西将令牌包含在我的 post/ajax 调用中

data: { 
        "__RequestVerificationToken":
        $("input[name=__RequestVerificationToken]").val() 
    },

但是...我正在使用 ViewModels 并创建我的视图模型对象,分配我的值,然后对其进行 JSON.stringify 处理并将其作为数据传递(如下所示)

        // Ajax call here
    // Make a view model instance
    var ajaxEditPermissionViewModel = new Object();
    ajaxEditPermissionViewModel.HasPermission = isChecked;
    ajaxEditPermissionViewModel.Permission = permission;
    ajaxEditPermissionViewModel.Category = category;
    ajaxEditPermissionViewModel.MembershipRole = role;

    // Ajax call to post the view model to the controller
    var strung = JSON.stringify(ajaxEditPermissionViewModel);

    $.ajax({
        url: '/Admin/Permissions/UpdatePermission',
        type: 'POST',
        dataType: 'json',
        data: strung,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            ResetTableAfterAjaxCall();
            ShowSuccessNotification();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            ShowUserMessage("Error: " + xhr.status + " " + thrownError);
            ResetTableAfterAjaxCall();
        }
    });

我有点困惑如何使用当前设置传递令牌?非常感谢任何建议。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 jquery antiforgerytoken


    【解决方案1】:

    您认为需要对结果进行字符串化是否有特定原因?我们只是这样做..

        $.ajax({
            type: "POST",
            data: {
                permission: Permission, 
                // other fields
            }...
    

    请参阅这篇文章了解如何使用这种传递参数的方式传递令牌:

    http://weblogs.asp.net/dixin/archive/2010/05/22/anti-forgery-request-recipes-for-asp-net-mvc-and-ajax.aspx

    【讨论】:

    • 我确实读过,如果您发布 JSON,则不需要令牌?你觉得这听起来对吗?
    猜你喜欢
    • 2019-01-28
    • 2016-07-18
    • 1970-01-01
    • 2015-07-21
    • 2014-04-08
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多