POSTからのユーザー入力HTML文字列をモデルオブジェクトの単純文字列変数にバインドしようとしています。これは、[AllowHtml]
属性を使用すると問題なく動作します。HTML文字列のカスタムモデルバインダーの使用
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
:しかし、私はModelBinderを作成しているので、それがモデルにその方法を作る前に、HTMLのサニタイズしたい
[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;
}
}
私は、モデルのプロパティに注釈を付けます私は新しい属性で消毒することにしたい:これはhttp://msdn.microsoft.com/en-us/magazine/hh781022.aspxでの例を以下れる
[Required(AllowEmptyStrings = false, ErrorMessage = "You must fill in your profile summary")]
[AllowHtml, SafeHtmlModelBinder, WordCount(Min = 1, Max = 300)]
public string Summary { get; set; }
。残念ながら、それは動作していないようです! BindModel
メソッドにブレークポイントを置くと、決してヒットしません。何か案は?私はSetProperty
方法で時に値を傍受し、代わりにHTMLを含めることができます文字列プロパティを含むクラスにSafeHtmlModelBinderAttribute
を適用するために私のIModelBinderを変更したジョエルからの情報に基づいて
UPDATE
。コードは、プロパティが文字列であり、またサニタイズしようとする前にHTMLを含むように許可されていることを確認します:私はちょうど同じことに苦しんできた
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);
}
}
CustomModelBinderAttributeはプロパティで動作しますか?この属性は、内部const AttributeTargetsでのみ使用されるMVCソースコードを参照してください。ValidTargets = AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct; '...これは、フレームワークがプロパティでこれを見ることを期待していないかもしれないことを示唆しています。 – Schneider