include antiforgerytoken in ajax post ASP.NET MVC

后端 未结 11 2406
感动是毒
感动是毒 2020-11-22 14:00

I am having trouble with the AntiForgeryToken with ajax. I\'m using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solu

11条回答
  •  醉话见心
    2020-11-22 14:42

    You have incorrectly specified the contentType to application/json.

    Here's an example of how this might work.

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(string someValue)
        {
            return Json(new { someValue = someValue });
        }
    }
    

    View:

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
    {
        @Html.AntiForgeryToken()
    }
    
    
    Click me to send an AJAX request to a controller action decorated with the [ValidateAntiForgeryToken] attribute

提交回复
热议问题