के लिए कस्टम मॉडल बाइंडर का उपयोग करके मैं एक मॉडल से इनपुट स्ट्रिंग वैरिएबल में एक POST से उपयोगकर्ता द्वारा इनपुट की गई HTML स्ट्रिंग को बाध्य करने का प्रयास कर रहा हूं। अगर मैं [AllowHtml]
विशेषता का उपयोग करता हूं तो यह ठीक काम करता है। हालांकि, मैं एचटीएमएल स्वच्छ करना चाहते हैं इससे पहले कि यह मॉडल में अपनी राह बनाता तो मैं एक ModelBinder बनाया है:एचटीएमएल स्ट्रिंग्स
public class SafeHtmlModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerCtx, ModelBindingContext bindingCtx)
{
var bound = base.BindModel(controllerCtx, bindingCtx);
// TODO - return a safe HTML fragment string
return bound;
}
}
और यह भी एक CustomModelBinderAttribute
:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class SafeHtmlModelBinderAttribute : CustomModelBinderAttribute
{
public SafeHtmlModelBinderAttribute()
{
binder = new SafeHtmlModelBinder();
}
private IModelBinder binder;
public override IModelBinder GetBinder()
{
return binder;
}
}
मैं तो मॉडल गुण व्याख्या मैं नई विशेषता के साथ स्वच्छ होना चाहते हैं जो:
[Required(AllowEmptyStrings = false, ErrorMessage = "You must fill in your profile summary")]
[AllowHtml, SafeHtmlModelBinder, WordCount(Min = 1, Max = 300)]
public string Summary { get; set; }
यह http://msdn.microsoft.com/en-us/magazine/hh781022.aspx में उदाहरण का पालन करना है। दुर्भाग्य से, यह काम नहीं लग रहा है! अगर मैं अपने BindModel
विधि में ब्रेकपॉइंट डालता हूं तो यह कभी हिट नहीं होता है। कोई विचार?
अद्यतन
जानकारी जोएल से मैं अपने IModelBinder बदल दिया है जब SetProperty
विधि में मूल्य रोकना और इसके बजाय क्लास वाली स्ट्रिंग गुण है कि HTML शामिल कर सकते हैं करने के लिए SafeHtmlModelBinderAttribute
लागू के आधार पर। कोड की जाँच करता है कि संपत्ति के एक स्ट्रिंग है और यह भी साफ़ करने में प्रयास करने से पहले एचटीएमएल शामिल करने के लिए अनुमति दी है:
public class SafeHtmlModelBinder : DefaultModelBinder
{
protected override void SetProperty(
ControllerContext controllerCtx,
ModelBindingContext bindingCtx,
PropertyDescriptor property,
object value)
{
var propertyIsString = property.PropertyType == typeof(string);
var propertyAllowsHtml = property.Attributes.OfType<AllowHtmlAttribute>().Count() >= 1;
var input = value as string;
if (propertyIsString && propertyAllowsHtml && input != null)
{
// TODO - sanitize HTML
value = input;
}
base.SetProperty(controllerCtx, bindingCtx, property, value);
}
}
क्या कस्टममोडेलबिन्डर एट्रिब्यूट गुणों पर काम करते हैं?एमवीसी स्रोत कोड को देखते हुए विशेषता का उपयोग केवल 'आंतरिक कॉन्स विशेषताएँ लक्ष्य ValidTargets = विशेषताTargets.Class पर किया जाता है। विशेषता लक्ष्य। ज्ञान | विशेषता लक्ष्य। इंटरफेस | विशेषता लक्ष्य। पैरामीटर | विशेषता लक्ष्य। संरचना; '... जो मुझे बताता है कि ढांचे को गुणों पर यह देखने की उम्मीद नहीं है। – Schneider