// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ModelBinding.Internal; namespace Microsoft.AspNet.Mvc.ModelBinding { /// /// ModelBinder to bind Byte Arrays. /// public class ByteArrayModelBinder : IModelBinder { /// public async Task BindModelAsync([NotNull] ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(byte[])) { return false; } var valueProviderResult = await bindingContext.ValueProvider.GetValueAsync(bindingContext.ModelName); // case 1: there was no element containing this data if (valueProviderResult == null) { return false; } var value = valueProviderResult.AttemptedValue; // case 2: there was an element but it was left blank if (string.IsNullOrEmpty(value)) { return false; } try { bindingContext.Model = Convert.FromBase64String(value); } catch (Exception ex) { ModelBindingHelper.AddModelErrorBasedOnExceptionType(bindingContext, ex); } return true; } } }