• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Metadata.ModelMetadataProvider类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Web.Http.Metadata.ModelMetadataProvider的典型用法代码示例。如果您正苦于以下问题:C# ModelMetadataProvider类的具体用法?C# ModelMetadataProvider怎么用?C# ModelMetadataProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ModelMetadataProvider类属于System.Web.Http.Metadata命名空间,在下文中一共展示了ModelMetadataProvider类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
        }
开发者ID:flyeven,项目名称:Utility,代码行数:41,代码来源:SimplePostVariableParameterBinding.cs


示例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");
        }
开发者ID:arpitgold,项目名称:Exceptionless,代码行数:28,代码来源:NakedParameterBinding.cs


示例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();
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:26,代码来源:ModelBinderParameterBinding.cs


示例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;
        }
开发者ID:RWE-Nexus,项目名称:EnergyTrading-MDM,代码行数:26,代码来源:ETagParameterBinding.cs


示例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");
        }
开发者ID:finsaspa,项目名称:Caravan,代码行数:37,代码来源:NakedBodyParameterBinding.cs


示例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;
        }
开发者ID:acprofessionale,项目名称:aspnetwebstack,代码行数:34,代码来源:ModelBinderParameterBinding.cs


示例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()));
                    });
        }
开发者ID:pawlos,项目名称:transferujpl-net,代码行数:32,代码来源:TransferujPlResponseModelBinder.cs


示例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);
		}
开发者ID:jango2015,项目名称:FluentValidation,代码行数:35,代码来源:FluentValidationBodyModelValidator.cs


示例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);
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:27,代码来源:FormatterParameterBindingTracer.cs


示例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;
        }
开发者ID:siddiquep,项目名称:DD4T.RestService.WebApi,代码行数:25,代码来源:CustomParamBinder.cs


示例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();
        }
开发者ID:tugberkugurlu,项目名称:WebAPIDoodle,代码行数:8,代码来源:PrincipalParameterBinding.cs


示例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();
        }        
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:11,代码来源:HttpRequestParameterBinding.cs


示例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);
 }
开发者ID:stevenaw,项目名称:climax-web-http,代码行数:9,代码来源:InjectParameterBinding.cs


示例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;
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:10,代码来源:PrincipalParameterBinding.cs


示例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();
        }
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:10,代码来源:ModelBinderParameterBinding.cs


示例16: ModelMetadata

        internal ModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, EfficientTypePropertyKey<Type, string> cacheKey)
            : this(provider, containerType, modelAccessor, modelType, propertyName)
        {
            if (cacheKey == null)
            {
                throw Error.ArgumentNull("cacheKey");
            }

            _cacheKey = cacheKey;
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:10,代码来源:ModelMetadata.cs


示例17: ExecuteBindingAsync

        public override async Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            NameValueCollection col = await ReadBodyAsync(actionContext.Request);
            if (col == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            // Set the binding result here
            SetValue(actionContext, col[Descriptor.ParameterName]);
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:11,代码来源:MultipleParameterFromBodyParameterBinding.cs


示例18: ExecuteBindingAsync

        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) {
            var binding = actionContext.ActionDescriptor.ActionBinding;

            var parameterBinding = binding.ParameterBindings.FirstOrDefault(b => b.Descriptor.ParameterBinderAttribute is UserAgentAttribute);
            if (parameterBinding == null || parameterBinding.Descriptor.ParameterType != typeof(string))
                return Task.FromResult(0);

            SetValue(actionContext, actionContext.Request.Headers.UserAgent.ToString());

            return Task.FromResult(0);
        }
开发者ID:arpitgold,项目名称:Exceptionless,代码行数:11,代码来源:UserAgentParameterBinding.cs


示例19: ExecuteBindingAsync

 public override Task ExecuteBindingAsync(
     ModelMetadataProvider metadataProvider, 
     HttpActionContext actionContext,
     CancellationToken cancellationToken)
 {
     var paramFromBody = Descriptor;
     var type = paramFromBody.ParameterType;
     var request = actionContext.ControllerContext.Request;
     var formatterLogger = new ModelStateFormatterLogger(actionContext.ModelState, paramFromBody.ParameterName);
     return ExecuteBindingAsyncCore(metadataProvider, actionContext, paramFromBody, type, request, formatterLogger, cancellationToken);
 }
开发者ID:jaredrussell,项目名称:Amikiri,代码行数:11,代码来源:BodyAndUriParameterBinding.cs


示例20: ExecuteBindingAsync

        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            IEnumerable<string> values;
            if (actionContext.Request.Headers.TryGetValues(this.name, out values))
            {
                actionContext.ActionArguments[this.Descriptor.ParameterName] = values.FirstOrDefault();
            }

            var taskSource = new TaskCompletionSource<object>();
            taskSource.SetResult(null);
            return taskSource.Task;
        }
开发者ID:tekconf,项目名称:TekAuth,代码行数:12,代码来源:FromHeaderBinding.cs



注:本文中的System.Web.Http.Metadata.ModelMetadataProvider类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ModelBinding.ModelBindingContext类代码示例发布时间:2022-05-26
下一篇:
C# Metadata.ModelMetadata类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap