过滤字符串的 vNext Model Binder

vNext Model Binder that filter strings

我需要过滤项目中的所有字符串以防止 XSS 攻击。 我决定使用全局模型活页夹来做到这一点。 您可以在下面看到模型活页夹注册码:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddMvcOptions(options =>
    {
        options.ModelBinders.Add(new AntiXSSModelBinder());
    });
}

要求过滤简单参数字符串和复杂类型(任何嵌套级别)内的字符串:

public async Task<IActionResult> GetShippingAddress(string id)
public async Task<IActionResult> AddUpdateShippingMethod(AddUpdateShippingMethodModel model)
// AddUpdateShippingMethodModel has Text property of string type

过滤方法示例:

public class AntiXSSModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {
        // ...
    }

    private string FilterPotentiallyXSSEntries(string value)
    {
        return value.Replace("<", "").Replace(">", "").Replace("script", "");
    }
}

没有关于 ModelBinder 主题的良好文档,因此我们将不胜感激。

public class AntiXSSModelBinder : IModelBinder
{
    public Task<ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelMetadata.IsComplexType)
        {
            // this type cannot be converted
            return ModelBindingResult.NoResultAsync;
        }

        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == ValueProviderResult.None)
        {
            // no entry
            return ModelBindingResult.NoResultAsync;
        }

        var model = valueProviderResult.ConvertTo(bindingContext.ModelType);

        if (bindingContext.ModelType == typeof(string))
        {
            var modelAsString = model as string;

            if (model != null)
            {
                return ModelBindingResult.SuccessAsync(bindingContext.ModelName, FilterPotentiallyXSSEntries(modelAsString));
            }
        }

        return ModelBindingResult.NoResultAsync;
    }

    private static string FilterPotentiallyXSSEntries(string value)
    {
        return value.Replace("<", "").Replace(">", "").Replace("script", "");
    }
}

适用于所有级别的嵌套。