2015-06-20 102 views
15

請問@Html.AntiForgeryToken()在ASP.NET .NET4.6 vNext中仍然需要嗎?Html.AntiForgeryToken()仍然需要?

形式裝飾品已更改爲

<form asp-controller="Account" 
     asp-action="Login" 
     asp-route-returnurl="@ViewBag.ReturnUrl" 
     method="post" 
     class="form-horizontal" 
     role="form"> 

從這個

@using (Html.BeginForm("Login", 
         "Account", 
         new { ReturnUrl = ViewBag.ReturnUrl }, 
         FormMethod.Post, 
         new { @class = "", role = "form" })) 

,不再包括這

@Html.AntiForgeryToken() 

的控制器操作仍標有ValidateAntiForgeryToken屬性如預期儘管如此,它是從哪裏來的?自動的?

[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) 

回答

32

表單標籤助手會自動添加防僞造令牌。 (除非您將其用作標準html表單元素,請手動添加action屬性)。檢查form tag helper的源代碼,您會在Process方法的末尾看到以下內容。

if (Antiforgery ?? antiforgeryDefault) 
{ 
    var antiforgeryTag = Generator.GenerateAntiforgery(ViewContext); 
    if (antiforgeryTag != null) 
    { 
     output.PostContent.AppendHtml(antiforgeryTag); 
    } 
} 

如果您檢查登錄頁面的HTML,你會看到表單中下面的隱藏輸入:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8BIeHClDdT9..."> 

您也可以手動啓用/禁用添加asp-antiforgery屬性:

<form asp-controller="Account" asp-action="Register" asp-antiforgery="false" method="post" class="form-horizontal" role="form"> 
+4

從MVC 6開始,Asp.net 5 RC1 Tag Helper是「asp-antiforgery」而不是「asp-anti-forgery」,不知道它是否已經是這樣或者已經改變了。
'

' –

相關問題