[C#] ASP.NET Core 6.0 - 一種可以將 Page 當 WebAPI 用的方法 + __RequestVerificationToken

2023-02-07

繼續上一篇文章 ( ASP.NET Core 6.0 - 一種可以將 Page 當 WebAPI 用的方法,但不推薦 )沒說得事情,其實是有一個方法

可以增加安全性不用加上  [IgnoreAntiforgeryToken] ,還是適當的增加了安全性可以簡單防禦了 XSRF/CSRF 攻擊

但是不一樣的是上一篇文章,你可以純用 .html 去用 AJAX 呼叫,但是這不行只能乖乖地開 Page


維持上一篇我們簡單建立一個 Page 來當作 Service ,跟原本不一樣的 就是不用加上  [IgnoreAntiforgeryToken]

SimpleEchoPostAFT.cshtml

@page @model Core6Tutorial.Pages.SimpleEchoPostAFTModel @{ Layout = null; } @Html.Raw(Model.Result)

SimpleEchoPostAFT.cshtml.cs

public class SimpleEchoPostAFTModel : PageModel { public string Result { get; set; } public void OnGet() { Result = "Call Get Method - AFT"; } public void OnPost(string firstname, string lastname) { Result = firstname + "," + lastname +" -- AFT"; } }


現在來看呼叫端

這時候在  Razor Page  部分 即使畫面沒有 Form 你可以使用   @Html.AntiForgeryToken() 將頁面直接擁有

<input name="__RequestVerificationToken" type="hidden" value="VerificationTokenValue" />


IgnoreAntiforgeryTokenTest.cshtml

@page @model Core6Tutorial.Pages.AntiforgeryTokenTestModel @{ } @Html.AntiForgeryToken() @section Scripts { <script> var aft = document.getElementsByName("__RequestVerificationToken")[0].value var http = new XMLHttpRequest(); var params = "firstname=" + "當麻" + "&lastname=" + "許"; http.open("POST", "SimpleEchoPostAFT", true); http.setRequestHeader("RequestVerificationToken", aft); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send(params); http.onreadystatechange = function() { if (http.readyState === XMLHttpRequest.DONE) { if (http.readyState === 4 && http.status === 200) { alert(http.responseText); } else { console.error(http.responseText); } } }; </script> }


這時候前端畫面就會 render 出來 __RequestVerificationToken 的 input

簡單的說只要畫面的東西就沒有 javascript 做不到的? 提取 __RequestVerificationToken 資料後直接放入 httprequest

就成功了,這跟上一篇文章 ( ASP.NET Core 6.0 - 一種可以將 Page 當 WebAPI 用的方法,但不推薦 ) 各有利弊

就看你的抉擇了..

reference:

https://blog.csdn.net/WuLex/article/details/119784238?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-8-119784238-blog-122729893.pc_relevant_default&spm=1001.2101.3001.4242.5&utm_relevant_index=11


當麻許的碎念筆記 2014 | Donma Hsu Design.