ASP.NET MVC-Html默认编码所有字符串

问题描述 投票:0回答:2

例如,用户在论坛上创建新问题。

我将ajax发送到服务器,然后使用HtmlEncode排除HTML代码,然后将其保存在数据库中。

是否有可能在收到请求时自动使用HtmlEncode?

此外,在使用属性(例如[HtmlAllowed])时,您可以在请求中允许html代码。

谢谢

asp.net-mvc asp.net-mvc-5
2个回答
1
投票

您可以使用自定义模型绑定器来实现,当ASP.NET尝试将请求绑定到操作方法的参数时,每个字符串属性或字符串参数都将通过此方法。>

public class StringBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

        var str = (string)value?.ConvertTo(typeof(string));

        str = HttpUtility.HtmlEncode(str);
        return str;
    }
}

并且在Application_Start()中>

ModelBinders.Binders.Add(typeof(string), new StringBinder());

感谢pwrigshihanomoronimo,为我指明了正确的方向。

此ModelBinder自动编码所有字符串属性,但具有[SafeHtml]属性的除外

public class SafeStringModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        HttpRequestBase request = controllerContext.HttpContext.Request;
        string name = bindingContext.ModelName;
        string value = request.Unvalidated[name];

        Type holderType = bindingContext.ModelMetadata.ContainerType;
        if (holderType != null)
        {
            PropertyInfo propertyType = holderType.GetProperty(bindingContext.ModelMetadata.PropertyName);
            if (propertyType == null) return value;

            object[] attributes = propertyType.GetCustomAttributes(true);
            bool hasAttribute = attributes.Cast<Attribute>().Any(a => a.GetType() == typeof (SafeHtmlAttribute));

            if (!hasAttribute && !string.IsNullOrEmpty(value))
            {
                value = HttpUtility.HtmlEncode(value);
            }
        }

        return value;
    }
}

[AttributeUsage(AttributeTargets.Property)]
public class SafeHtmlAttribute : Attribute { }

0
投票

感谢pwrigshihanomoronimo,为我指明了正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.