2011-06-10 93 views
0

我見過有關關閉控制器/操作的HttpRequestValidation以解決此錯誤的幾篇文章,但我真的希望它在大多數情況下啓用。很少有足夠的情況下,我想繞過我願意環繞它一個try/catch塊驗證:ASP.Net MVC HttpRequestValidationException - 捕獲錯誤和捕獲輸入?

string searchTerm = string.Empty; 
try { 
    searchTerm = Request.QueryString["q"]; 
} catch (HttpRequestValidationException ex) { 
    // What can I do here to capture the value? Is parsing the error message the only way? 
    // Seems like ex.Data property would be a good place for Microsoft to stick values if 
    // people wanted to do something with them, but ex.Data is empty. 
} 

同樣,這只是形式的某些字段,所以我不希望禁用整個控制器或操作的驗證。我想爲那些我沒有特別處理的領域提供額外的保護。

回答

2

您是否檢查了AllowHTML屬性?這可能正是你需要的。

public class MyModel 
{ 
    public string ValidatedField {get; set;} // no HTML allowed here! 

    [AllowHtml] 
    public string NonValidatedField {get; set;} // user can enter HTML 
} 
+0

完美,謝謝。只需要創建一個視圖模型,而不是直接從查詢字符串中獲取它。 – Sam 2011-06-10 14:42:42