Skip to content
Loading
anti-forgery form field"__RequestVerificationToken" is not present    
  •                 
  •                 
  •                
  •             class="panel-footer">    
  •                 "button" class="btn btn-primary Comment" data-id="@Model.BlogPublishedByBlogId.BlogId" value="Comment">    
  •                     class="glyphicon glyphicon-comment" aria-hidden="true"> Get Comment(s)    
  •                     
  •                 
  •             "@string.Format("{0}_{1}","commentsBlock", @Model.BlogPublishedByBlogId.BlogId)" style="border: 1px solid #f1eaea; background-color: #eaf2ff;">    
  •                 class="AddCommentArea" style="margin-left: 30%;  margin-bottom: 5px; margin-top: 8px;">    
  •                     @Html.AntiForgeryToken()    
  •                     "text" id="@string.Format("{0}_{1}", "comment", @Model.BlogPublishedByBlogId.BlogId)" class="form-control" placeholder="Add a comment..." style="display: inline;" />    
  •                     "button" class="btn btn-primary addComment" data-id="@Model.BlogPublishedByBlogId.BlogId">class="glyphicon glyphicon-comment" aria-hidden="true">    
  •                     
  •                 
  •             
  •         
  •     }    
  •     
  •     @Scripts.Render("~/bundles/jqueryval")    
  •     @Scripts.Render("~/bundles/jquery")    
  •     @Scripts.Render("~/bundles/bootstrap")    
  •     @Styles.Render("~/Content/css")    
  •     
  •     @section Scripts    
  •     {    
  •     "text/javascript">    
  •         $(document).ready(function () {    
  •             $('.Comment').on('click'function () {    
  •                 var blogId = $(this).attr("data-id");    
  •                 var allCommentsArea = $('
    ').addClass('allComments_' + blogId);    
  •     
  •                 $.ajax({    
  •                     type: 'GET',    
  •                     url: '@Url.Action("GetBlogComments", "BlogPublished")',    
  •                     data: { blogId: blogId },    
  •                     success: function (response) {    
  •                         if ($('div').hasClass('allComments_' + blogId + ''))    
  •                         {    
  •                             $('div[class=allComments_' + blogId + ']').remove();    
  •                         }    
  •     
  •                         // Dynamically building the HTML to hold the comments (the list) returned.    
  •                         // The area for the BlogPublished/_Comments.cshtml to be placed.    
  •                         allCommentsArea.html(response);    
  •                         allCommentsArea.prependTo('#commentsBlock_' + blogId);    
  •                     },    
  •                     error: function (xhr, ajaxOptions, thrownError) {    
  •                         alert("Critical Error: something is wrong in the call to GetBlogComments! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText);    
  •                     }    
  •                 })    
  •             });    
  •     
  •             // For when clicking the 'addComment' button.    
  •             $('.addComment').on('click'function () {    
  •                 var blogId = $(this).attr('data-id');    
  •                 var blogCommentContent = $('#comment_' + blogId).val();    
  •                 var dateTimeNow = new Date();    
  •                 var userProfileProcessType = "I";    
  •     
  •                 // An object - the BlogComment model to be passed to the controller method.    
  •                 var blogComment = {    
  •                     BlogId: blogId,    
  •                     BlogCommentContent: blogCommentContent,    
  •                     DateTimeOfBlogComment: dateTimeNow.toLocaleString()    
  •                 };    
  •       
  •                 $.ajax({    
  •                     type: 'POST',    
  •                     url: '@Url.Action("ProcessSaveBlogComment", "BlogPublished")',    
  •                     data: AddAntiForgeryToken({ blogComment, userProfileProcessType }),    
  •                     success: function (response) {    
  •                         $('div[class=allComments_' + blogId + ']').remove();   
  •                         // Dynamically building the HTML to hold the comments (the list) returned which now includes the added comment.    
  •                         var allCommentsArea = $('
    ').addClass('allComments_' + blogId);    
  •                         allCommentsArea.html(response);    
  •                         allCommentsArea.prependTo('#commentsBlock_' + blogId);  
  •                         $("#comment_" + blogId).val('')    
  •                     },    
  •                     error: function (xhr, ajaxOptions, thrownError) {    
  •                         alert("Critical Error: something is wrong in the call to ProcessSaveBlogComment! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText);    
  •                     }    
  •                 });    
  •             });   
  •             jQuery(".timeago").timeago();    
  •         });   
  •         AddAntiForgeryToken = function (data) {    
  •             data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();    
  •             return data;    
  •         };    
  •         
  •     }   
  •  Here is the controller:
    1. [HttpPost][ValidateAntiForgeryToken]  
    2. public async Task ProcessSaveBlogComment(BlogComment blogComment, string userProfileProcessType) {  
    3.   if (ModelState.IsValid) {  
    4.     blogComment.UserId = Convert.ToInt32(Session["UserId"]);  
    5.     BLL_BlogPublished bll_BlogPublished = new BLL_BlogPublished();  
    6.     ProcessSaveBlogCommentResults processSaveBlogCommentResults = new ProcessSaveBlogCommentResults();  
    7.   
    8.     try {  
    9.       processSaveBlogCommentResults = await bll_BlogPublished.ProcessSaveBlogComment(blogComment, Session["UserName"].ToString(), userProfileProcessType);  
    10.   
    11.       if (processSaveBlogCommentResults.ApiErrorMessage == null) {  
    12.         if (processSaveBlogCommentResults.Status == 2) {  
    13.           ViewBag.errormessage = "Process Violation: You are not the 'blog comment' creator so you cannot update the blog comment.";  
    14.         }  
    15.         else if (processSaveBlogCommentResults.Status == 3) {  
    16.           ViewBag.errormessage = "Process Violation: Not the correct 'blog id' so cannot update the blog comment.";  
    17.         }  
    18.       }  
    19.       else {  
    20.         ViewBag.errormessage = processSaveBlogCommentResults.ApiErrorMessage;  
    21.       }  
    22.     }  
    23.     catch(Exception ex1) {  
    24.       exceptionMessage = "Server error on saving the blog comment. Please contact the administrator.";  
    25.   
    26.       try {  
    27.         ClientErrorResult clientErrorResult = new ClientErrorResult();  
    28.   
    29.         clientErrorResult = await ProcessClientError(Session["UserName"].ToString(), ex1.Message, "Server error on saving the blog comment. User name: " + Session["UserName"] + ". Post method: ProcessSaveBlogComment.");  
    30.   
    31.         if (clientErrorResult.ApiErrorMessage == null) {  
    32.           ViewBag.errormessage = exceptionMessage;  
    33.         }  
    34.         else {  
    35.           ViewBag.errormessage = clientErrorResult.ApiErrorMessage;  
    36.         }  
    37.       }  
    38.       catch(Exception ex2) {  
    39.         ViewBag.errormessage = "Failure in ProcessClientError. Exception error: " + ex2.Message + ". Original error: " + exceptionMessage;  
    40.       }  
    41.     }  
    42.   }  
    43.   
    44.   return RedirectToAction("GetBlogComments""BlogPublished"new {  
    45.     blogId = blogComment.BlogId  
    46.   });  
    47. }   
    Before leaving the AddAntiForgeryToken function - the console log.
     
     
     
    The network tab - cookies.
     
     
     
    Part 1 of the Network tab - header (has the request verification token in the cookie).
     
     
    Part 2 of the Network tab - header (has my data to send to the controller).
     
     
    Error:
    8/13/2020 4:49:56 PM
    ------------------------------------------------------------------------------------------------
    Controller Name :- BlogPublished
    Action Method Name :- ProcessSaveBlogComment
    ------------------------------------------------------------------------------------------------
    System.Web.Mvc.ExceptionContext
    Message ---
    {0}The required anti-forgery form field "__RequestVerificationToken" is not present.
    .Net Error ---
    {0}Check MVC Ajax Code For Error
    Source ---
    {0}System.Web.WebPages
    StackTrace ---
    {0} at System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
    at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext)
    at System.Web.Helpers.AntiForgery.Validate()
    at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext)
    at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
    at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.b__0(AsyncCallback asyncCallback, Object asyncState)
    TargetSite ---
    {0}Void ValidateTokens(System.Web.HttpContextBase, System.Security.Principal.IIdentity, System.Web.Helpers.AntiXsrf.AntiForgeryToken, System.Web.Helpers.AntiXsrf.AntiForgeryToken)

    1 Reply

    Know the answer? Post it — somebody with the same question will find it here.