LoginSignup
1
4

More than 5 years have passed since last update.

[ASP.NET Core 2.1]AJAXでAntiForgeryTokenを使う

Last updated at Posted at 2018-09-21

RequestVerificationTokenヘッダにトークンを入れてあげる。
コードを見た方が早い。

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf

$.ajax({
    url: "/test",
    headers: { "RequestVerificationToken":"@(Xsrf.GetAndStoreTokens(Context).RequestToken)" }
}).done(function (result) {
}).fail(function () {
}).always(function () {
})

なお、あまり無いとは思うけど、popoverのコンテンツに使うなどの理由でinput要素ごと埋め込みたいときはこうする。

@using System.IO;

@{
    var writer = new StringWriter();
    Html.AntiForgeryToken().WriteTo(writer, HtmlEncoder);
    var token = writer.ToString();
    var content= $@"
<form action=""/test"" method=""post"">
    {token}
</form>
";
}
1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4