簡體   English   中英

返回JSON 500錯誤-所需的反偽造表單字段“ __RequestVerificationToken”不存在

[英]Return JSON 500 error - The required anti-forgery form field “__RequestVerificationToken” is not present

我還看到了其他一些帖子,但是我還沒有找到可以解決我的特殊情況的帖子。 我試圖返回我的實體框架生成的模型類的JSON對象。 這是我的看法:

@{
    ViewBag.Title = "Clock In/Out";
    var currentEmployee = ViewBag.CurrentEmployee;
    var existingTimeEntry = ViewBag.ExistingTimeEntry;
    var btnValue = "";
    var btnClass = "";

    btnValue = currentEmployee.IsClockedIn == true ? "Clock Out" : "Clock In";
    btnClass = currentEmployee.IsClockedIn == true ? "clock-out-btn" : "clock-in-btn";
}

<header class="login-header">
    <div class="clearfix">
        <h1>@ViewBag.Title</h1>
    </div>
</header>
@{
    using (Html.BeginForm(null, null, FormMethod.Post, new { id = "clock-in-form" }))
    {
        @Html.AntiForgeryToken()
        <div class="clock-in-wrapper">
            <p class="text-center">You are currently logged in as @currentEmployee.FirstName @currentEmployee.LastName.</p>
            <input type="hidden" id="EmployeeID" name="EmployeeID" value="@currentEmployee.EmployeeID"/>
            <div class="row">
                <div class="col-md-12">
                    <input type="submit" value="@btnValue" class="btn btn-primary @btnClass" />
                </div>
            </div>
        </div>
     }
}

這是我的控制器:

// POST: TimeEntries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TimeEntryID,EmployeeID,TimeStart,TimeEnd,IsClosed")] TimeEntry timeEntry) {

    var currentUserId = User.Identity.GetUserId();
    var currentUser = db.AspNetUsers.FirstOrDefault(c => c.Id == currentUserId);
    var currentEmployee = db.Employees.FirstOrDefault(c => c.EmployeeID == currentUser.EmployeeID);
    ViewBag.CurrentEmployee = currentEmployee;
    var existingTimeEntry = db.TimeEntries.FirstOrDefault(te => te.EmployeeID == currentEmployee.EmployeeID && te.IsClosed == false);
    ViewBag.ExistingTimeEntry = existingTimeEntry;
    var timeEntryID = -1;

    if (existingTimeEntry != null)
    {
        timeEntryID = existingTimeEntry.TimeEntryID;
    }

    ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName");

    if (ModelState.IsValid)
    {
        if (timeEntryID <= 0)
        {
            // Grab the current employee and set clocked in to true.
            var employee = db.Employees.Find(timeEntry.EmployeeID);
            employee.IsClockedIn = true;

            // Create the time entry.
            timeEntry.TimeStart = DateTime.Now;
            timeEntry.IsClosed = false;
            db.TimeEntries.Add(timeEntry);

            ViewBag.CurrentTimeEntry = timeEntry;

            db.SaveChanges();

            return Json(timeEntry, JsonRequestBehavior.AllowGet);
        }
        else {
            var updatedTimeEntry = db.TimeEntries.Find(timeEntryID);
            var employee = db.Employees.Find(timeEntry.EmployeeID);

            employee.IsClockedIn = false;
            updatedTimeEntry.TimeEnd = DateTime.Now;
            updatedTimeEntry.IsClosed = true;

            db.SaveChanges();

            return Json(updatedTimeEntry, JsonRequestBehavior.AllowGet);
        }
    }

    ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", timeEntry.EmployeeID);
    return View(timeEntry);
}

這是我的jQuery:

$(function () {
    $("#clock-in-form").on("submit", function (e) {
        e.preventDefault();
        var submitButton = $("#clock-in-form input[type='submit']");
        var dt = new Date();
        var formData = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "/TimeEntries/Create",
            data: JSON.stringify(formData),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                if (submitButton.hasClass("clock-in-btn")) {
                    submitButton.removeClass("clock-in-btn");
                    submitButton.addClass("clock-out-btn");
                    submitButton.attr("value", "Clock Out");
                    console.log(data);
                    $(".clock-in-alerts").append('<div class="alert alert-success text-center">You have successfully logged in at ' + data.TimeStart + '.</div>');
                } else if (submitButton.hasClass("clock-out-btn")) {
                    submitButton.removeClass("clock-out-btn");
                    submitButton.addClass("clock-in-btn");
                    submitButton.attr("value", "Clock In");
                }
            },
            error: function (xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(error);
            }
        });
    });
});

當我嘗試提交表單時,出現內部服務器錯誤(500),並且在響應文本中顯示“所需的反偽造表單字段“ __RequestVerificationToken”不存在”。

您需要將防偽令牌添加到請求的標頭中。 您可以為每個請求執行此操作,也可以使用ajaxSetup將其添加到每個請求中。

嘗試這樣的事情:

jQuery(document).ready(function ($) {
    $.ajaxSetup({
        type: "POST",
        headers: { "__RequestVerificationToken": $('[name=__RequestVerificationToken]').val() }
    });
});

查看相關問題以獲取更多信息: jQuery Ajax調用和Html.AntiForgeryToken()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM