本文整理汇总了C#中System.Web.Http.Metadata.ModelMetadataProvider类的典型用法代码示例。如果您正苦于以下问题:C# ModelMetadataProvider类的具体用法?C# ModelMetadataProvider怎么用?C# ModelMetadataProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ModelMetadataProvider类属于System.Web.Http.Metadata命名空间,在下文中一共展示了ModelMetadataProvider类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteBindingAsync
/// <summary>
/// Check for simple binding parameters in POST data. Bind POST
/// data as well as query string data
/// </summary>
/// <param name="metadataProvider"></param>
/// <param name="actionContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
HttpActionContext actionContext,
CancellationToken cancellationToken)
{
string stringValue = null;
NameValueCollection col = TryReadBody(actionContext.Request);
if (col != null)
stringValue = col[Descriptor.ParameterName];
// try reading query string if we have no POST/PUT match
if (stringValue == null)
{
var query = actionContext.Request.GetQueryNameValuePairs();
if (query != null)
{
var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower());
var keyValuePairs = matches as IList<KeyValuePair<string, string>> ?? matches.ToList();
if (keyValuePairs.Any())
stringValue = keyValuePairs.First().Value;
}
}
object value = StringToType(stringValue);
// Set the binding result here
SetValue(actionContext, value);
// now, we can return a completed task with no result
TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
tcs.SetResult(default(AsyncVoid));
return tcs.Task;
}
示例2: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) {
var binding = actionContext.ActionDescriptor.ActionBinding;
if (actionContext.Request.Method == HttpMethod.Get || binding.ParameterBindings.Count(b => b.Descriptor.ParameterBinderAttribute is NakedBodyAttribute) > 1)
return EmptyTask.Start();
var type = binding.ParameterBindings[0].Descriptor.ParameterType;
if (type == typeof(string)) {
return actionContext.Request.Content
.ReadAsStringAsync()
.ContinueWith(task => {
var stringResult = task.Result;
SetValue(actionContext, stringResult);
}, cancellationToken);
}
if (type == typeof(byte[])) {
return actionContext.Request.Content
.ReadAsByteArrayAsync()
.ContinueWith(task => {
byte[] result = task.Result;
SetValue(actionContext, result);
}, cancellationToken);
}
throw new InvalidOperationException("Only string and byte[] are supported for [NakedBody] parameters");
}
示例3: 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();
}
示例4: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
HttpActionContext actionContext, CancellationToken cancellationToken)
{
EntityTagHeaderValue etagHeader = null;
switch (this._match)
{
case ETagMatch.IfNoneMatch:
etagHeader = actionContext.Request.Headers.IfNoneMatch.FirstOrDefault();
break;
case ETagMatch.IfMatch:
etagHeader = actionContext.Request.Headers.IfMatch.FirstOrDefault();
break;
}
ETag etag = null;
if (etagHeader != null)
{
etag = new ETag { Tag = etagHeader.Tag };
}
actionContext.ActionArguments[this.Descriptor.ParameterName] = etag;
var tsc = new TaskCompletionSource<object>();
tsc.SetResult(null);
return tsc.Task;
}
示例5: ExecuteBindingAsync
/// <summary>
/// Asynchronously executes the binding for the given request.
/// </summary>
/// <returns>A task object representing the asynchronous operation.</returns>
/// <param name="metadataProvider">Metadata provider to use for validation.</param>
/// <param name="actionContext">
/// The action context for the binding. The action context contains the parameter
/// dictionary that will get populated with the parameter.
/// </param>
/// <param name="cancellationToken">Cancellation token for cancelling the binding operation.</param>
public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
var request = actionContext.Request;
if (request.Method == HttpMethod.Get)
{
SetValue(actionContext, null);
return;
}
var type = Descriptor.ParameterType;
if (type == typeof(Stream))
{
var streamResult = await request.Content.ReadAsStreamAsync();
SetValue(actionContext, streamResult);
return;
}
if (type == typeof(byte[]))
{
var byteArrayResult = await request.Content.ReadAsByteArrayAsync();
SetValue(actionContext, byteArrayResult);
return;
}
throw new InvalidOperationException("Only byte[] and Stream are supported for [NakedBody] parameters");
}
示例6: GetModelBindingContext
private ModelBindingContext GetModelBindingContext(ModelMetadataProvider metadataProvider, HttpActionContext actionContext)
{
string name = Descriptor.ParameterName;
Type type = Descriptor.ParameterType;
string prefix = Descriptor.Prefix;
IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);
if (_metadataCache == null)
{
Interlocked.Exchange(ref _metadataCache, metadataProvider.GetMetadataForType(null, type));
}
ModelBindingContext ctx = new ModelBindingContext()
{
ModelName = prefix ?? name,
FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
ModelMetadata = _metadataCache,
ModelState = actionContext.ModelState,
ValueProvider = vp
};
if (_validationNodeCache == null)
{
Interlocked.Exchange(ref _validationNodeCache, ctx.ValidationNode);
}
else
{
ctx.ValidationNode = _validationNodeCache;
}
return ctx;
}
示例7: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
var log = NLog.LogManager.GetCurrentClassLogger();
log.Info("ExecuteBindingAsync");
var binding = actionContext.ActionDescriptor.ActionBinding;
if (actionContext.Request.GetClientIpAddress() != "195.149.229.109" &&
actionContext.Request.IsLocal() == false)
{
log.Info("Invalid IP - Expecting 195.149.229.109, got: {0}",
actionContext.Request.Headers.Host);
throw new InvalidOperationException("Invalid IP.");
}
var type = binding.ParameterBindings[0].Descriptor.ParameterType;
if (type != typeof(TransferujPlResponse))
{
log.Info("Invalid parameter type. Expecting TransferujPlResponse");
throw new InvalidOperationException();
}
return actionContext.Request.Content
.ReadAsStringAsync()
.ContinueWith((task) =>
{
var stringResult = task.Result;
log.Debug("Detailed info: {0}", stringResult);
SetValue(actionContext, TransferujPlResponse.FromNameValueCollection(
stringResult.ToNameValueCollection()));
});
}
示例8: Validate
public bool Validate(object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, string keyPrefix) {
if (type == null) {
throw new ArgumentNullException("type");
}
if (metadataProvider == null) {
throw new ArgumentNullException("metadataProvider");
}
if (actionContext == null) {
throw new ArgumentNullException("actionContext");
}
if (model != null && MediaTypeFormatterCollection.IsTypeExcludedFromValidation(model.GetType())) {
// no validation for some DOM like types
return true;
}
ModelValidatorProvider[] validatorProviders = actionContext.GetValidatorProviders().ToArray();
// Optimization : avoid validating the object graph if there are no validator providers
if (validatorProviders == null || validatorProviders.Length == 0) {
return true;
}
ModelMetadata metadata = metadataProvider.GetMetadataForType(() => model, type);
ValidationContext validationContext = new ValidationContext {
MetadataProvider = metadataProvider,
ActionContext = actionContext,
ModelState = actionContext.ModelState,
Visited = new HashSet<object>(),
KeyBuilders = new Stack<IKeyBuilder>(),
RootPrefix = keyPrefix
};
return this.ValidateNodeAndChildren(metadata, validationContext, container: null);
}
示例9: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
return _traceWriter.TraceBeginEndAsync(
actionContext.Request,
TraceCategories.ModelBindingCategory,
TraceLevel.Info,
_innerBinding.GetType().Name,
ExecuteBindingAsyncMethodName,
beginTrace: (tr) =>
{
tr.Message = Error.Format(SRResources.TraceBeginParameterBind,
_innerBinding.Descriptor.ParameterName);
},
execute: () => _innerBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken),
endTrace: (tr) =>
{
string parameterName = _innerBinding.Descriptor.ParameterName;
tr.Message = actionContext.ActionArguments.ContainsKey(parameterName)
? Error.Format(SRResources.TraceEndParameterBind, parameterName,
FormattingUtilities.ValueToString(actionContext.ActionArguments[parameterName], CultureInfo.CurrentCulture))
: Error.Format(SRResources.TraceEndParameterBindNoBind,
parameterName);
},
errorTrace: null);
}
示例10: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,
CancellationToken cancellationToken)
{
//TODO: VALIDATION & ERROR CHECKS
string idsAsString = actionContext.Request.GetRouteData().Values["ids"].ToString();
idsAsString = idsAsString.Trim('[', ']');
IEnumerable<string> ids = idsAsString.Split(',');
ids = ids.Where(str => !string.IsNullOrEmpty(str));
IEnumerable<int> idList = ids.Select(strId =>
{
if (string.IsNullOrEmpty(strId)) return -1;
return Convert.ToInt32(strId);
}).ToArray();
SetValue(actionContext, idList);
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
return tcs.Task;
}
示例11: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
string name = Descriptor.ParameterName;
IPrincipal principal = Thread.CurrentPrincipal;
actionContext.ActionArguments.Add(name, principal);
return TaskHelpers.Completed();
}
示例12: ExecuteBindingAsync
// Execute the binding for the given request.
// On success, this will add the parameter to the actionContext.ActionArguments dictionary.
// Caller ensures IsError==false.
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
string name = Descriptor.ParameterName;
HttpRequestMessage request = actionContext.ControllerContext.Request;
actionContext.ActionArguments.Add(name, request);
return TaskHelpers.Completed();
}
示例13: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (actionContext.ControllerContext.Configuration.DependencyResolver != null)
{
var resolved = actionContext.Request.GetDependencyScope().GetService(Descriptor.ParameterType);
actionContext.ActionArguments[Descriptor.ParameterName] = resolved;
}
return Task.FromResult(0);
}
示例14: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
// Set the binding result here
SetValue(actionContext, new GenericPrincipal(new GenericIdentity("MyIdentity"), new string[]{"myrole"}));
// now, we can return a completed task with no result
TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
tcs.SetResult(default(AsyncVoid));
return tcs.Task;
}
示例15: ExecuteBindingAsync
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
ModelBindingContext ctx = GetModelBindingContext(metadataProvider, actionContext);
bool haveResult = _binder.BindModel(actionContext, ctx);
object model = haveResult ? ctx.Model : Descriptor.DefaultValue;
SetValue(actionContext, model);
return TaskHelpers.Completed();
}