/// <summary> /// Binds the model. /// </summary> /// <typeparam name="T">Model type</typeparam> /// <param name="args">The <see cref="ModelBinderEventArgs{T}" /> instance containing the event data.</param> public async Task BindAsync <T>(ModelBinderEventArgs <T> args) { if (!args.Context.Request.ContentType.Contains("multipart/form-data")) { return; } var multipartModelType = typeof(MultipartViewModel); if (typeof(T) != multipartModelType) { throw new ModelBindingException("For HTTP multipart form data model type should be: " + multipartModelType.Name); } var parser = await MultipartFormDataParser.ParseAsync(args.Context.Request.Body); var obj = Activator.CreateInstance <T>(); var model = (MultipartViewModel)(object)obj; model.Files = parser.Files; model.Parameters = parser.Parameters; args.SetModel(obj); }
private static void Validate <T>(ModelBinderEventArgs <T> args, IDIResolver resolver) { foreach (var validator in ModelValidatorsTypes.Select(x => (IModelValidator)resolver.Resolve(x))) { validator.Validate(args.Model, resolver); } }
/// <summary> /// Binds specified form data to model. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public void Bind <T>(ModelBinderEventArgs <T> args) { if (args.Context.Request.ContentType.Contains("application/x-www-form-urlencoded")) { args.SetModel( ListToModelParser.Parse <T>(args.Context.Form.Select(x => new KeyValuePair <string, string[]>(x.Key, x.Value)).ToList())); } }
/// <summary> /// Binds specified HTTP query to model. /// </summary> /// <typeparam name="T">Model type</typeparam> /// <param name="args">The <see cref="ModelBinderEventArgs{T}" /> instance containing the event data.</param> public void Bind <T>(ModelBinderEventArgs <T> args) { if (args.Context.Request.Method == "GET") { args.SetModel( ListToModelParser.Parse <T>( args.Context.Query.Select(x => new KeyValuePair <string, string[]>(x.Key, x.Value)).ToList())); } }
/// <summary> /// Parses model and validates it asynchronously /// </summary> /// <typeparam name="T">Model type</typeparam> /// <param name="resolver">The resolver.</param> /// <returns></returns> public async Task <T> ProcessAsync <T>(IDIResolver resolver) { var args = new ModelBinderEventArgs <T>(_context); foreach (var binder in ModelBindersTypes.Select(binderType => (IModelBinder)resolver.Resolve(binderType))) { await binder.BindAsync(args); if (!args.IsBound) { continue; } Validate(args, resolver); return(args.Model); } throw new ModelBindingException($"Unrecognized request content type for binding: {_context.Request.ContentType}"); }