Last active
December 7, 2017 09:51
-
-
Save stevejgordon/28faee35cbedbb936f062dd103a3ec5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class HtmlEncodeModelBinder : IModelBinder | |
| { | |
| private readonly IModelBinder _fallbackBinder; | |
| public HtmlEncodeModelBinder(IModelBinder fallbackBinder) | |
| { | |
| if (fallbackBinder == null) | |
| throw new ArgumentNullException(nameof(fallbackBinder)); | |
| _fallbackBinder = fallbackBinder; | |
| } | |
| public Task BindModelAsync(ModelBindingContext bindingContext) | |
| { | |
| if (bindingContext == null) | |
| throw new ArgumentNullException(nameof(bindingContext)); | |
| var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); | |
| if (valueProviderResult == ValueProviderResult.None) | |
| { | |
| return _fallbackBinder.BindModelAsync(bindingContext); | |
| } | |
| var valueAsString = valueProviderResult.FirstValue; | |
| if (string.IsNullOrEmpty(valueAsString)) | |
| { | |
| return _fallbackBinder.BindModelAsync(bindingContext); | |
| } | |
| var result = HtmlEncoder.Default.Encode(valueAsString); | |
| bindingContext.Result = ModelBindingResult.Success(result); | |
| return Task.CompletedTask; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment