2012-11-18 62 views

回答

4

沒有自動方式。您可以做的最接近的是獲得AntiXss Nuget包。然後你可以使用它下面喜歡在你的控制器:

Microsoft.Security.Application.Sanitizer.GetSafeHtml("YourHtml"); 

OR

Microsoft.Security.Application.Encoder.HtmlEncode("YourHtml"); 

如果你使用,你可以使用

Server.HtmlDecode("HtmlEncodedString"); 

希望這有助於解碼。

10

首先,afaik,沒有什麼內置的。 但MVC允許通過自定義ModelBinders容易做出這樣的事情,你可以定義你的

public class CustomAntiXssAttribute : Attribute { } 

,並用它裝點您的屬性(如果你願意,甚至從AllowHtmlAttribute繼承)。然後用模型綁定你可以添加你的具體的反XSS防護:

public class CutstomModelBinder : DefaultModelBinder 
    { 
     protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) 
     { 
      if (propertyDescriptor.Attributes.OfType<CustomAntiXssAttribute>().Any()) 
      { 
       var valueResult = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); 
       var filteredValue = SOME_CUSTOM_FILTER_FUNCTION_HERE(valueResult.AttemptedValue); 
       propertyDescriptor.SetValue(bindingContext.Model, filteredValue); 
      } 
      else // revert to the default behavior. 
      { 
       base.BindProperty(controllerContext, bindingContext, propertyDescriptor); 
      } 
     } 
    } 

那麼這裏面SOME_CUSTOM_FILTER_FUNCTION_HERE你可以使用什麼@Yogiraj建議,或使用正則表達式,甚至申請HtmlAgilityPack,基於內容的過濾。

P.S.不要忘記添加ModelBinders.Binders.DefaultBinder = new CutstomModelBinder();到的Application_Start(我忘了:))

+3

你不能繼承所有ALLOWHTMLATTRIBUTE 「這是一個密封類」 – VJAI

0

未經測試的代碼,

public class ADefaultModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelMetadata.RequestValidationEnabled) 
     { 
      var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue; 
      value = value.Replace("&", "");// replace existing & from the value 
      var encodedValue = Microsoft.Security.Application.Encoder.HtmlEncode(value); 
      bindingContext.ModelMetadata.RequestValidationEnabled = encodedValue.Contains("&"); // Whether AntiXss encoded a char to &.. 
     } 
     return base.BindModel(controllerContext, bindingContext); 
    } 
} 
public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     ModelBinders.Binders.DefaultBinder = new ADefaultModelBinder(); 
1

我會去更換那些AllowHtmlRegularExpression數據註釋驗證屬性。優點是通過這種方式,您可以捕捉錯誤並向用戶顯示錯誤發生了什麼,而前者在全球範圍內觸發錯誤。

例如,

public class MyViewModel 
{ 
    [DataType(DataType.MultilineText)] 
    [RegularExpression(@"^[^\<\>]*$", ErrorMessage = "May not contain <,>")] 
    public string Text { get; set; } 
} 

編號:RegularExpression validator encoding regex < & > symbols as &lt; &gt;, causing jQuery validation to fail