Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 从jTable到MVC5执行CRUD项目时,如何传递防伪令牌?_Asp.net Mvc_Antiforgerytoken - Fatal编程技术网

Asp.net mvc 从jTable到MVC5执行CRUD项目时,如何传递防伪令牌?

Asp.net mvc 从jTable到MVC5执行CRUD项目时,如何传递防伪令牌?,asp.net-mvc,antiforgerytoken,Asp.net Mvc,Antiforgerytoken,当从jTable向MVC5控制器执行CRUD调用时,如何传递AntiForgeryToken?为了完成该操作,我必须注释掉ValidateAntiForgeryToken部分,该部分看起来相当不安全。如果没有,则会收到“与服务器通信时出错”消息 jTable代码: $(document).ready(function () { //Prepare jtable plugin $('#CandidateTable').jtable({ title: 'Ca

当从jTable向MVC5控制器执行CRUD调用时,如何传递AntiForgeryToken?为了完成该操作,我必须注释掉ValidateAntiForgeryToken部分,该部分看起来相当不安全。如果没有,则会收到“与服务器通信时出错”消息

jTable代码:

    $(document).ready(function () {

    //Prepare jtable plugin
    $('#CandidateTable').jtable({
        title: 'Candidates',
        actions: {
            listAction: '@Url.Action("List")',
            deleteAction: '@Url.Action("Delete")',
            updateAction: '@Url.Action("Edit")',
            createAction: '@Url.Action("Create")'
        },
        fields: {
            ID: {
                key: true,
                create: false,
                edit: false,
                list: false
            },
            FirstName: {
                title: '@Html.DisplayNameFor(model => model.FirstName)',
                width: '15%'
            },
            MiddleName: {
                title: '@Html.DisplayNameFor(model => model.MiddleName)',
                width: '15%'
            },
            LastName: {
                title: '@Html.DisplayNameFor(model => model.LastName)',
                width: '15%'
            },
            AnonymousID: {
                title: '@Html.DisplayNameFor(model => model.AnonymousID)',
                width: '15%'
            },
            Email: {
                title: '@Html.DisplayNameFor(model => model.Email)',
                width: '15%'
            },
            GUID: {
                title: '@Html.DisplayNameFor(model => model.GUID)',
                width: '15%',
                create: false,
                edit: false
            }
        }
    });

    //Load person list from server
    $('#CandidateTable').jtable('load');
});
ASP.NET MVC 5创建操作:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Create([Bind(Include = "FirstName,MiddleName,LastName,AnonymousID,Email")] Candidate candidate)
    {
        try
        {
            if (ModelState.IsValid)
            {
                candidate.GUID = System.Guid.NewGuid();
                candidate.IsActive = true;
                candidate.DateAdded = DateTime.Now.ToUniversalTime();
                candidate.DateModified = null;
                db.Candidates.Add(candidate);
                db.SaveChanges();

                return Json(new { Result = "OK", Record = candidate });
            }
            else
            {
                throw new Exception("Form is not valid! Please correct it and try again.");
            }                
        }
        catch (Exception ex)
        {                
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            return Json(new { Result = "ERROR", Message = ex.Message });
        }            
    }
更新:

我想出来了。我需要添加一个任意字段(AFT),然后添加一个@HTML.AntiForgeryToken输出的自定义输入。现在我只需要弄清楚如何在Delete上执行此操作,因为Delete只传递主键(id)


首先要做的是在
视图中添加一个函数,该函数将生成您的防伪令牌:

@functions{
    public string TokenHeaderValue()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;                
    }
}
@functions
块允许您将函数添加到
视图中。它们有助于将您的所有功能保持在一个位置,从而有助于组织

然后,在Javascript中进行AJAX调用,并将令牌添加为
RequestVerificationToken
头:

$.ajax("api/values", {
    type: "post",
    contentType: "application/json",
    data: {  }, // JSON data goes here
    dataType: "json",
    headers: {
        'RequestVerificationToken': '@TokenHeaderValue()' //Can be named whatever
    }
});
现在在解决方案中创建以下实用程序方法:

void ValidateRequestHeader(HttpRequestMessage request)
{
    string cookieToken = "";
    string formToken = "";

    IEnumerable<string> tokenHeaders;
    if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
    {
        string[] tokens = tokenHeaders.First().Split(':');
        if (tokens.Length == 2)
        {
            cookieToken = tokens[0].Trim();
            formToken = tokens[1].Trim();
        }
    }
    AntiForgery.Validate(cookieToken, formToken);
}

ref:

我有这个代码,也许它会帮助你。我猜jtable使用$.ajax作为它的请求,所以我想它应该可以工作

// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.type.toUpperCase() === "POST") {
        // We need to add the verificationToken to all POSTs
        var token = $("input[name^=__RequestVerificationToken]").eq(0);
        var headers = {};
        headers["__RequestVerificationToken"] = token.val();
        if (!token.length) return;

        var tokenName = token.attr("name");

        // If the data is JSON, then we need to put the token in the QueryString:
        if (options.contentType.indexOf('application/json') === 0) {
           // Add the token to the URL, because we can't add it to the JSON data:
           options.headers = headers;
        } 
   }
}); 

我已经找到了如何添加这个AntiForgeryToken来删除jTable的操作。您已将
\uuuuu AFT\uuuuuu
正确添加到创建和更新操作中,无需添加标题和获取控制器。要将其添加到删除操作,您可以编写自定义删除,如下所示。更新了你的代码

var tokenId = '@Html.AntiForgeryToken()';

$('#CandidateTable').jtable({
    paging: true,
    pageSize: 15,
    sorting: true,
    defaultSorting: 'LastName ASC',
    title: 'Candidates',
    actions: {
        listAction: '@Url.Action("List")',
        deleteAction: function (postData) {
            postData.__RequestVerificationToken = $(tokenId).val();
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '@Url.Action("Delete")',
                    type: 'POST',
                    dataType: 'json',
                    data: postData,
                    success: function (data) {
                        $dfd.resolve(data);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        },
        updateAction: '@Url.Action("Edit")',
        createAction: '@Url.Action("Create")'
    },
    fields: {
        ID: {
            key: true,
            create: false,
            edit: false,
            list: false
        },
        FirstName: {
            title: '@Html.DisplayNameFor(model => model.FirstName)',
            width: '15%'
        },
        MiddleName: {
            title: '@Html.DisplayNameFor(model => model.MiddleName)',
            width: '15%'
        },
        LastName: {
            title: '@Html.DisplayNameFor(model => model.LastName)',
            width: '15%'
        },
        AnonymousID: {
            title: '@Html.DisplayNameFor(model => model.AnonymousID)',
            width: '15%'
        },
        Email: {
            title: '@Html.DisplayNameFor(model => model.Email)',
            width: '15%'
        },                
        __AFT__: {
            create: true,
            edit: true,
            list: false,
            input: function (data) {
                return tokenId;
            }
        }

    }

我自己也试过了。希望这能有所帮助。

我使用的解决方案通常是使用防伪令牌的值向请求添加一个自定义头,然后在服务器上进行检查。但是,我不确定如何使用jTable实现这一点。如果你想要一个简单的AJAX示例的指导,让我知道。哦,非常酷的方法。我的方式确实有点“哈奇”,谢谢@kcabrams:请添加更新作为答案,对我有用,但是的,它对另一个伟大的解决方案不起作用。谢谢你。
// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.type.toUpperCase() === "POST") {
        // We need to add the verificationToken to all POSTs
        var token = $("input[name^=__RequestVerificationToken]").eq(0);
        var headers = {};
        headers["__RequestVerificationToken"] = token.val();
        if (!token.length) return;

        var tokenName = token.attr("name");

        // If the data is JSON, then we need to put the token in the QueryString:
        if (options.contentType.indexOf('application/json') === 0) {
           // Add the token to the URL, because we can't add it to the JSON data:
           options.headers = headers;
        } 
   }
}); 
var tokenId = '@Html.AntiForgeryToken()';

$('#CandidateTable').jtable({
    paging: true,
    pageSize: 15,
    sorting: true,
    defaultSorting: 'LastName ASC',
    title: 'Candidates',
    actions: {
        listAction: '@Url.Action("List")',
        deleteAction: function (postData) {
            postData.__RequestVerificationToken = $(tokenId).val();
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '@Url.Action("Delete")',
                    type: 'POST',
                    dataType: 'json',
                    data: postData,
                    success: function (data) {
                        $dfd.resolve(data);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        },
        updateAction: '@Url.Action("Edit")',
        createAction: '@Url.Action("Create")'
    },
    fields: {
        ID: {
            key: true,
            create: false,
            edit: false,
            list: false
        },
        FirstName: {
            title: '@Html.DisplayNameFor(model => model.FirstName)',
            width: '15%'
        },
        MiddleName: {
            title: '@Html.DisplayNameFor(model => model.MiddleName)',
            width: '15%'
        },
        LastName: {
            title: '@Html.DisplayNameFor(model => model.LastName)',
            width: '15%'
        },
        AnonymousID: {
            title: '@Html.DisplayNameFor(model => model.AnonymousID)',
            width: '15%'
        },
        Email: {
            title: '@Html.DisplayNameFor(model => model.Email)',
            width: '15%'
        },                
        __AFT__: {
            create: true,
            edit: true,
            list: false,
            input: function (data) {
                return tokenId;
            }
        }

    }