vNext模型Binder过滤字符串

时间:2016-03-09 09:04:14

标签: c# asp.net-mvc asp.net-core-mvc model-binding modelbinders

我需要过滤项目中的所有字符串以防止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主题的好文档,因此我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

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", "");
    }
}

适用于所有级别的嵌套。