[筆記]Dotnet Core MVC 不使用Form透過Ajax Post 通過 ValidateAntiForgeryToken 驗證

Successfully verified through Ajax Post and ValidateAntiForgeryToken

透過Ajax Post並成功通過ValidateAntiForgeryToken 驗證

不使用Form

 

View

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    @Html.AntiForgeryToken()
    <button id="test">Test</button>
</div>

@section Scripts{
    <script src="~/js/main.js" asp-append-version="true"></script>
}

Controller

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace PostValidate.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Test(string input)
        {
            return Json(input);
        }

    }
}

JS

$(document).on("click", "#test", function () {
    PostToTest("Hello");
});

function PostToTest(param) {
    var token = $("input[name='__RequestVerificationToken']").val();
    let postObj = {};
    postObj["input"] = param;
    postObj["__RequestVerificationToken"] = token;
    let postData = $.param(postObj);
    $.ajax({
        type: "POST",
        url: `/Home/Test`,
        data: postData,
        success: function (result) {
            console.log(result);
        }
    });
}

測試結果