我已经在多个地方读过,防止XSS的正确方法是不清理输入,而是在显示输出之前对输出进行html编码。
但是,我认为我遇到了规则的例外情况。我有一些数据存储在数据库中,这些数据由我无法控制的其他遗留应用程序使用,这些应用程序可能会也可能不会对输出进行编码。
答案 0 :(得分:3)
首先创建一个ActionFilterAttribute:
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Microsoft.Security.Application;
/// <summary>
/// Sanitizes (HTML encodes) all strings on the model.
/// </summary>
/// <remarks>Use sparingly. Ideally don't use this and instead encode when outputting the values.
/// This is used because we don't have control of other applications that may consume the data.</remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class SanitizeInputAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ActionArguments != null && actionContext.ActionArguments.Count == 1)
{
var requestParam = actionContext.ActionArguments.First();
var properties = requestParam.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => x.CanRead && x.CanWrite && x.PropertyType == typeof(string) && x.GetGetMethod(true).IsPublic && x.GetSetMethod(true).IsPublic);
foreach (var propertyInfo in properties)
{
propertyInfo.SetValue(requestParam.Value, Encoder.HtmlEncode(propertyInfo.GetValue(requestParam.Value) as string));
}
}
}
}
然后只需在类或行动上注册它:
[HttpPost]
[SanitizeInput]
public Response Post(Object model)
{...}