简体   繁体   English

带有JSON.Stringify的ASP.NET Core 2.2 AntiForgeryToken

[英]ASP.NET Core 2.2 AntiForgeryToken with JSON.Stringify

I have this controller on my server that has a ValidateAntiForgeryToken attribute 我的服务器上有一个具有ValidateAntiForgeryToken属性的控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetHistory([FromBody] ChatMessageGetHistoryViewModel Input)
{
     var userName = HttpContext.User.Claims.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault();
     var history = chatMessageData.GetAllBySessionId(Input.SessionId, userName);
     var output = JsonConvert.SerializeObject(history);
     return Ok(output);
}

I have tried this method but so far I keep getting the error code 400. I have tried including the antiforgery token as part of the form data but that also doesn't work. 我已经尝试过这种方法,但到目前为止我一直得到错误代码400.我已经尝试将反antiforgery令牌作为表单数据的一部分,但这也不起作用。

<script>
    $(document).ready(function () {
        var token = $('input[name="__RequestVerificationToken"]', $('#__AjaxAntiForgeryForm')).val();
        var SessionId = document.getElementById("Id").value;
        var form_data = {
            "SessionId": SessionId,
            __RequestVerificationToken: token,
        };
        $.ajax({
            url: "@Url.Action("GetHistory", @ViewContext.RouteData.Values["controller"].ToString())",
            method: "POST",
            data: JSON.stringify(form_data),
            contentType: "application/json",
            success: function (result) {
                console.log(result);
                var output = JSON.parse(result);
                for (var i = 0; i < output.length; i++) {
                    var p = document.createElement("span");
                    var q = document.createElement("li");
                    if (output[i].Mine == true) {
                        p.setAttribute("class", "Sender Me");
                        q.setAttribute("class", "Message");
                    } else {
                        p.setAttribute("class", "Sender");
                        q.setAttribute("class", "Message");
                    }
                    p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
                    q.textContent = output[i].Message;
                    document.getElementById("MessageList").appendChild(p);
                    document.getElementById("MessageList").appendChild(q);
                }

            },
            error: function (error) {
                console.log(error);
            }
        });

        $('#MessageList').stop().animate({
            scrollTop: $('#MessageList')[0].scrollHeight
        }, 2000);
        return false;
    });
</script>

You have to pass the RequestVerificationToken as header with ajax request as follows: 您必须使用ajax请求将RequestVerificationToken作为header传递,如下所示:

$.ajax({
        url: "@Url.Action("GetHistory", @ViewContext.RouteData.Values["controller"].ToString())",
        method: "POST",
        data: JSON.stringify(form_data),
        contentType: "application/json",
        headers: { 'RequestVerificationToken': token }, // here have to set the token
        success: function (result) {
            console.log(result);
            var output = JSON.parse(result);
            for (var i = 0; i < output.length; i++) {
                var p = document.createElement("span");
                var q = document.createElement("li");
                if (output[i].Mine == true) {
                    p.setAttribute("class", "Sender Me");
                    q.setAttribute("class", "Message");
                } else {
                    p.setAttribute("class", "Sender");
                    q.setAttribute("class", "Message");
                }
                p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
                q.textContent = output[i].Message;
                document.getElementById("MessageList").appendChild(p);
                document.getElementById("MessageList").appendChild(q);
            }

        },
        error: function (error) {
            console.log(error);
        }
    });

For AJAX requests, you need to set the token in the request headers: the RequestVerificationToken request header, specifically, by default. 对于AJAX请求,您需要在请求标头中设置令牌: RequestVerificationToken请求标头,具体而言,默认情况下。

$.ajax({
    ...
    headers: {
        'RequestVerificationToken': token
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM