本文整理汇总了C#中System.Web.Http.ModelBinding.ModelBindingContext类的典型用法代码示例。如果您正苦于以下问题:C# ModelBindingContext类的具体用法?C# ModelBindingContext怎么用?C# ModelBindingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ModelBindingContext类属于System.Web.Http.ModelBinding命名空间,在下文中一共展示了ModelBindingContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BindModel
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(Hash))
return false;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null)
return false;
string valueStr = value.RawValue as string;
if (valueStr == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type.");
return false;
}
Hash result;
try
{
result = Hash.Parse(valueStr);
}
catch
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot parse hash.");
return false;
}
bindingContext.Model = result;
return true;
}
示例2: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var val = bindingContext.ValueProvider.GetValue(key);
if (val != null)
{
var s = val.AttemptedValue;
if (s != null)
{
var elementType = bindingContext.ModelType.GetElementType();
var converter = TypeDescriptor.GetConverter(elementType);
var values = Array.ConvertAll(s.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });
var typedValues = Array.CreateInstance(elementType, values.Length);
values.CopyTo(typedValues, 0);
bindingContext.Model = typedValues;
}
else
{
// change this line to null if you prefer nulls to empty arrays
bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
}
return true;
}
return false;
}
示例3: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (actionContext == null)
{
throw new ArgumentNullException("actionContext");
}
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
try
{
// Try to parse as Json
bindingContext.Model = Parse(content);
}
catch (Exception)
{
// Parse the QueryString
_queryString = GetQueryString(content);
bindingContext.Model = Parse(_queryString);
}
return true;
}
示例4: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
//NOTE: Validation is done in the filter
if (!actionContext.Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var root = HttpContext.Current.Server.MapPath("~/App_Data/TEMP/FileUploads");
//ensure it exists
Directory.CreateDirectory(root);
var provider = new MultipartFormDataStreamProvider(root);
var task = Task.Run(() => GetModel(actionContext.Request.Content, provider))
.ContinueWith(x =>
{
if (x.IsFaulted && x.Exception != null)
{
throw x.Exception;
}
bindingContext.Model = x.Result;
});
task.Wait();
return bindingContext.Model != null;
}
示例5: BindModel
public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
BindModelOnSuccessOrFail(bindingContext,
() => ModelBinderUtils.CreateSingleValueArgument(DeserializeContent(actionContext)),
ModelBinderUtils.CreateSingleValueArgumentForMalformedArgs);
return true;
}
示例6: GetDateTime
private static DateTime GetDateTime(ModelBindingContext context, string prefix, string key)
{
var dateValue = GetValue(context, prefix, key);
dateValue = dateValue.Replace("\"", string.Empty);
dateValue = dateValue.Split('T')[0];
return TryParser.DateTime(dateValue) ?? DateTime.Today;
}
示例7: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var jsonStr = actionContext.Request.Content.ReadAsStringAsync().Result;
var msgObj = Json.Decode(jsonStr);
bindingContext.Model = new Msg
{
UserName = msgObj.UserName,
Email = msgObj.Email,
HomePage = msgObj.HomePage,
Text = msgObj.Text,
Date = DateTime.Now
};
var captchaValidtor = new Recaptcha.RecaptchaValidator
{
PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"],
RemoteIP = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress,
Challenge = msgObj.recaptcha_challenge_field,
Response = msgObj.recaptcha_response_field
};
var recaptchaResponse = captchaValidtor.Validate();
if (!recaptchaResponse.IsValid)
{
actionContext.ModelState.AddModelError("recaptcha_response_field", "Символы не соответствуют картинке.");
}
return true;
}
示例8: BindModel
public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(coreModel.SearchCriteria))
{
return false;
}
var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query as string);
var result = new coreModel.SearchCriteria();
result.Keyword = qs["q"].EmptyToNull();
var respGroup = qs["respGroup"].EmptyToNull();
if (respGroup != null)
{
result.ResponseGroup = EnumUtility.SafeParse<coreModel.ResponseGroup>(respGroup, coreModel.ResponseGroup.Default);
}
result.StoreIds = qs.GetValues("stores");
result.CustomerId = qs["customer"].EmptyToNull();
result.EmployeeId = qs["employee"].EmptyToNull();
result.Count = qs["count"].TryParse(20);
result.Start = qs["start"].TryParse(0);
bindingContext.Model = result;
return true;
}
示例9: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
DemoVector vector;
if (bindingContext.ModelType != typeof (DemoVector))
{
return false;
}
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null)
{
return false;
}
var text = value.RawValue as string;
if (DemoVector.TryParse(text, out vector))
{
bindingContext.Model = vector;
return true;
}
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to vector.");
return false;
}
示例10: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var nvc = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
var model = new GetPagedListParams
{
PageSize = int.Parse(nvc["count"]),
Page = int.Parse(nvc["page"]),
SortExpression = "Id"
};
var sortingKey = nvc.AllKeys.FirstOrDefault(x => x.StartsWith("sorting["));
if (sortingKey != null)
{
model.SortExpression = sortingKey.RemoveStringEntries("sorting[", "]") + " " + nvc[sortingKey];
}
model.Filters = nvc.AllKeys.Where(x => x.StartsWith("filter["))
.ToDictionary(x => x.RemoveStringEntries("filter[", "]"), y => nvc[y]);
if (nvc.AllKeys.Contains("filter"))
{
model.Filters = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(nvc["filter"]);
}
bindingContext.Model = model;
return true;
}
示例11: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
// Try to resolve hero
ValueProviderResult heroValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Hero));
Hero hero = null;
if (!string.IsNullOrWhiteSpace(heroValue?.AttemptedValue))
{
Guid heroId = _cryptographyService.DecryptGuid(heroValue.AttemptedValue);
hero = _heroRepository.GetHero(heroId);
}
// Try to resolve begin
ValueProviderResult beginValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Begin));
DateTime? begin = null;
DateTime beginTry;
if (!string.IsNullOrWhiteSpace(beginValue?.AttemptedValue) && DateTime.TryParse(beginValue.AttemptedValue, out beginTry))
{
begin = beginTry;
}
// Try to resolve end
ValueProviderResult endValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.End));
DateTime? end = null;
DateTime endTry;
if (!string.IsNullOrWhiteSpace(endValue?.AttemptedValue) && DateTime.TryParse(endValue.AttemptedValue, out endTry))
{
end = endTry;
}
bindingContext.Model = new FreeToPlayPeriodPropertiesModel(hero, begin, end);
return true;
}
示例12: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
string name = Descriptor.ParameterName;
Type type = Descriptor.ParameterType;
string prefix = Descriptor.Prefix;
IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);
ModelBindingContext ctx = new ModelBindingContext()
{
ModelName = prefix ?? name,
FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
ModelMetadata = metadataProvider.GetMetadataForType(null, type),
ModelState = actionContext.ModelState,
ValueProvider = vp
};
IModelBinder binder = this._modelBinderProvider.GetBinder(actionContext, ctx);
bool haveResult = binder.BindModel(actionContext, ctx);
object model = haveResult ? ctx.Model : Descriptor.DefaultValue;
actionContext.ActionArguments.Add(name, model);
return TaskHelpers.Completed();
}
示例13: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(ObjectId))
{
return false;
}
var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (val == null)
{
return false;
}
var value = val.RawValue as string;
if (value == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
return false;
}
ObjectId result;
if (ObjectId.TryParse(value, out result))
{
bindingContext.Model = result;
return true;
}
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to location");
return false;
}
示例14: BindModel
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof (CriteriaModel))
{
return false;
}
var value = bindingContext.ValueProvider.GetValue("Categories");
if (value == null)
{
return false;
}
var categoryJson = value.RawValue as IEnumerable<string>;
if (categoryJson == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Categories cannot be null.");
return false;
}
var categories = categoryJson.Select(JsonConvert.DeserializeObject<CriteriaCategory>).ToList();
bindingContext.Model = new CriteriaModel {Categories = categories};
return true;
}
示例15: BindComplexCollectionFromIndexes_InfiniteIndexes
public void BindComplexCollectionFromIndexes_InfiniteIndexes()
{
// Arrange
CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR");
Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
ModelBindingContext bindingContext = new ModelBindingContext
{
ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
ModelName = "someName",
ValueProvider = new SimpleHttpValueProvider
{
{ "someName[0]", "42" },
{ "someName[1]", "100" },
{ "someName[3]", "400" }
}
};
HttpActionContext context = ContextUtil.CreateActionContext();
context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));
mockIntBinder
.Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
.Returns((HttpActionContext ec, ModelBindingContext mbc) =>
{
mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);
return true;
});
// Act
List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(context, bindingContext, null /* indexNames */);
// Assert
Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());
Assert.Equal(new[] { "someName[0]", "someName[1]" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());
}