1、防止跨站點(diǎn)提交
傳統(tǒng)mvc中,ValidateAntiForgeryToken特性用于防止跨站點(diǎn)數(shù)據(jù)提交,但是使用時(shí)必須配合前臺(tái)view頁面的Html.AntiForgeryToken()代碼一起使用。
而在asp.net core中,taghelper表單特性已經(jīng)將該特性包含在view中服務(wù)器特性代碼asp-action 或者asp-route中了,詳見TagHelper參考我的另一個(gè)博文http://www.rzrgm.cn/xiatianoo/p/6323245.html
2、防止過多提交
防止過多提交,及過多傳遞實(shí)體字段值,這時(shí)Bind特性就派上用場(chǎng)了,Bind特性限制傳遞的字段,同時(shí),配合Include,Exclude和TryUpdateModel參數(shù)來設(shè)置限定特殊字段。
假設(shè)有一個(gè)類Student,它用于和數(shù)據(jù)庫建立映射,而且Student中的一個(gè)字段Secret你不想在頁面上修改它的值。
public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public string Secret { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } }
即使界面上沒有Secret對(duì)應(yīng)的字段,hacker可以通過一些工具(如fildder)或者編寫js去發(fā)送請(qǐng)求來修改Secret的值。

如上圖,Secret的值會(huì)被修改為OverPost。
防止
在ASP.NET中,防止過多發(fā)布的方法大概有以下幾種:
1. 使用BindAttribute中的Include屬性,把需要映射的字段加到白名單。
public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student)
2. 使用BindAttribute中的Exclude屬性,把不允許映射的字段加到黑名單。
public ActionResult Create([Bind(Exclude = "Secret")]Student student)
3. 使用TryUpdateModel方法,驗(yàn)證Model的時(shí)候,制定需要映射的字段。
if (TryUpdateModel(student, "", new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
{
}
4. 定義一個(gè)新的類作為輸入?yún)?shù)
public class StudentForm
{
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
該博文參考原官方文檔:https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application#overpost
該博文參考大牛翻譯:http://www.rzrgm.cn/Erik_Xu/p/5497501.html
浙公網(wǎng)安備 33010602011771號(hào)