// Read the body upfront , add as a ValueProvider public override Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { HttpRequestMessage request = actionContext.ControllerContext.Request; HttpContent content = request.Content; if (content != null) { HttpParameterDescriptor fromBodyParam = null; //偵測是否有任何參數有[FromBody] if ((fromBodyParam = actionContext.ActionDescriptor .GetParameters().SingleOrDefault(o => o.GetCustomAttributes <FromBodyAttribute>().Any())) != null) { //若有,將Content內容JSON反列化為參數型別 var json = content.ReadAsStringAsync().Result; var value = JsonConvert.DeserializeObject(json, fromBodyParam.ParameterType); var vp = new NameValuePairsValueProvider(new Dictionary <string, object>() { [fromBodyParam.ParameterName] = value }, CultureInfo.CurrentCulture); request.Properties.Add(Key, vp); } else { FormDataCollection fd = content.ReadAsAsync <FormDataCollection>().Result; if (fd != null) { IValueProvider vp = new NameValuePairsValueProvider(fd, CultureInfo.InvariantCulture); request.Properties.Add(Key, vp); } } } return(base.ExecuteBindingAsync(actionContext, cancellationToken)); }
static void Main(string[] args) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("contacts[0].Name", "张三"); dictionary.Add("contacts[0].PhoneNo", "123456789"); dictionary.Add("contacts[0].EmailAddress", "*****@*****.**"); dictionary.Add("contacts[1].Name", "李四"); dictionary.Add("contacts[1].PhoneNo", "987654321"); dictionary.Add("contacts[1].EmailAddress", "*****@*****.**"); NameValuePairsValueProvider valueProvider = new NameValuePairsValueProvider(dictionary.ToArray(), null); //Prefix="" Console.WriteLine("Prefix: <Empty>"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); IDictionary <string, string> keys = valueProvider.GetKeysFromPrefix(string.Empty); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact" Console.WriteLine("\nPrefix: contact"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contacts[0]" Console.WriteLine("\nPrefix: contacts[0]"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contacts[0]"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contacts[1]" Console.WriteLine("\nPrefix: contacts[1]"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contacts[1]"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } }
// Read the body upfront , add as a ValueProvider public override Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { HttpRequestMessage request = actionContext.ControllerContext.Request; HttpContent content = request.Content; FormDataCollection fd = content?.ReadAsAsync <FormDataCollection>(cancellationToken).Result; if (fd != null) { IValueProvider vp = new NameValuePairsValueProvider(fd, CultureInfo.InvariantCulture); request.Properties.Add(Key, vp); } return(base.ExecuteBindingAsync(actionContext, cancellationToken)); }
static void Main(string[] args) { List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >(); list.Add(new KeyValuePair <string, string>("foobar", "1")); list.Add(new KeyValuePair <string, string>("foobar", "2")); list.Add(new KeyValuePair <string, string>("foobar", "3")); NameValuePairsValueProvider valueProvider = new NameValuePairsValueProvider(list, null); var result = valueProvider.GetValue("foobar"); int[] value1 = (int[])result.ConvertTo(typeof(int[])); int value2 = (int)result.ConvertTo(typeof(int)); Console.WriteLine("{0,-16}{1}", "RawValue", "NewValue"); Console.WriteLine("{0,-16}{1}", result.RawValue.ConvertToString(), value1.ConvertToString()); Console.WriteLine("{0,-16}{1}", result.RawValue.ConvertToString(), value2.ConvertToString()); }
static void Main(string[] args) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("contact.Name", "张三"); dictionary.Add("contact.PhoneNo", "123456789"); dictionary.Add("contact.EmailAddress", "*****@*****.**"); dictionary.Add("contact.Address.Province", "江苏"); dictionary.Add("contact.Address.City", "苏州"); dictionary.Add("contact.Address.District", "工业园区"); dictionary.Add("contact.Address.Street", "星湖街328号"); NameValuePairsValueProvider valueProvider = new NameValuePairsValueProvider(dictionary.ToArray(), null); //Prefix="" Console.WriteLine("Prefix: <Empty>"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); IDictionary <string, string> keys = valueProvider.GetKeysFromPrefix(string.Empty); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact" Console.WriteLine("\nPrefix: contact"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact.Address" Console.WriteLine("\nPrefix: contact.Address"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact.Address"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } }
// Read the body upfront, add as a ValueProvider public override Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { HttpRequestMessage request = actionContext.ControllerContext.Request; HttpContent content = request.Content; if (content != null) { string result = request.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(result)) { var jsonContent = JObject.Parse(result); var values = new Dictionary<string, object>(); foreach (HttpParameterDescriptor parameterDescriptor in actionContext.ActionDescriptor.GetParameters()) { object parameterValue = GetParameterValue(jsonContent, parameterDescriptor); values.Add(parameterDescriptor.ParameterName, parameterValue); } IValueProvider valueProvider = new NameValuePairsValueProvider(values, CultureInfo.InvariantCulture); request.Properties.Add(Key, valueProvider); } } return base.ExecuteBindingAsync(actionContext, cancellationToken); }
private object BindToModel(IDictionary <string, object> data, Type type, IFormatterLogger formatterLogger) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } using (var config = new HttpConfiguration()) { // if there is a requiredMemberSelector set, use this one by replacing the validator provider var validateRequiredMembers = RequiredMemberSelector != null && formatterLogger != null; if (validateRequiredMembers) { config.Services.Replace(typeof(ModelValidatorProvider), new RequiredMemberModelValidatorProvider(RequiredMemberSelector)); } // create a action context for model binding var actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Configuration = config, ControllerDescriptor = new HttpControllerDescriptor { Configuration = config } } }; // create model binder context var valueProvider = new NameValuePairsValueProvider(data, CultureInfo.InvariantCulture); var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider(); var metadata = metadataProvider.GetMetadataForType(null, type); var modelBindingContext = new ModelBindingContext { ModelName = string.Empty, FallbackToEmptyPrefix = false, ModelMetadata = metadata, ModelState = actionContext.ModelState, ValueProvider = valueProvider }; // bind model var modelBinderProvider = new CompositeModelBinderProvider(config.Services.GetModelBinderProviders()); var binder = modelBinderProvider.GetBinder(config, type); var haveResult = binder.BindModel(actionContext, modelBindingContext); // log validation errors if (formatterLogger != null) { foreach (var modelStatePair in actionContext.ModelState) { foreach (var modelError in modelStatePair.Value.Errors) { if (modelError.Exception != null) { formatterLogger.LogError(modelStatePair.Key, modelError.Exception); } else { formatterLogger.LogError(modelStatePair.Key, modelError.ErrorMessage); } } } } return(haveResult ? modelBindingContext.Model : GetDefaultValueForType(type)); } }
// apply dictionary to model instance private object BindToModel(IDictionary <string, object> data, Type type, IFormatterLogger formatterLogger) { if (data == null) { throw new ArgumentNullException(nameof(data)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } using (var config = new HttpConfiguration()) { if (RequiredMemberSelector != null && formatterLogger != null) { config.Services.Replace( typeof(ModelValidatorProvider), new RequiredMemberModelValidatorProvider(RequiredMemberSelector)); } var actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Configuration = config, ControllerDescriptor = new HttpControllerDescriptor { Configuration = config } } }; // workaround possible locale mismatch var cultureBugWorkaround = CultureInfo.CurrentCulture.Clone() as CultureInfo; cultureBugWorkaround.NumberFormat = CultureInfo.InvariantCulture.NumberFormat; var valueProvider = new NameValuePairsValueProvider(data, cultureBugWorkaround); var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider(); var metadata = metadataProvider.GetMetadataForType(null, type); var modelBindingContext = new ModelBindingContext { ModelName = string.Empty, FallbackToEmptyPrefix = false, ModelMetadata = metadata, ModelState = actionContext.ModelState, ValueProvider = valueProvider }; // bind our model var modelBinderProvider = new CompositeModelBinderProvider(config.Services.GetModelBinderProviders()); var binder = modelBinderProvider.GetBinder(config, type); var haveResult = binder.BindModel(actionContext, modelBindingContext); // store validation errors if (formatterLogger != null) { foreach (var modelStatePair in actionContext.ModelState) { foreach (var modelError in modelStatePair.Value.Errors) { if (modelError.Exception != null) { formatterLogger.LogError(modelStatePair.Key, modelError.Exception); } else { formatterLogger.LogError(modelStatePair.Key, modelError.ErrorMessage); } } } } return(haveResult ? modelBindingContext.Model : GetDefaultValueForType(type)); } }