当前位置: 首页>>代码示例>>C#>>正文


C# HttpRequestMessage.GetConfiguration方法代码示例

本文整理汇总了C#中System.Net.Http.HttpRequestMessage.GetConfiguration方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.GetConfiguration方法的具体用法?C# HttpRequestMessage.GetConfiguration怎么用?C# HttpRequestMessage.GetConfiguration使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpRequestMessage的用法示例。


在下文中一共展示了HttpRequestMessage.GetConfiguration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //得到描述目标Action的HttpActionDescriptor
            HttpMethod originalMethod = request.Method;
            bool isPreflightRequest = request.IsPreflightRequest();
            if (isPreflightRequest)
            {
                string method = request.Headers.GetValues("Access-Control-Request-Method").First();
                request.Method = new HttpMethod(method);
            }

            HttpConfiguration configuration = request.GetConfiguration();
            HttpControllerDescriptor controllerDescriptor = configuration.Services.GetHttpControllerSelector().SelectController(request);
            HttpControllerContext controllerContext = new HttpControllerContext(request.GetConfiguration(), request.GetRouteData(), request)
            {
                ControllerDescriptor = controllerDescriptor
            };
            HttpActionDescriptor actionDescriptor = configuration.Services.GetActionSelector().SelectAction(controllerContext);
            //根据HttpActionDescriptor得到应用的CorsAttribute特性
            CorsAttribute corsAttribute = actionDescriptor.GetCustomAttributes<CorsAttribute>().FirstOrDefault() ??
                controllerDescriptor.GetCustomAttributes<CorsAttribute>().FirstOrDefault();
            if (null == corsAttribute)
            {
                return base.SendAsync(request, cancellationToken);
            }
            //利用CorsAttribute实施授权并生成响应报头
            IDictionary<string, string> headers;
            request.Method = originalMethod;
            bool authorized = corsAttribute.TryEvaluate(request, out headers);
            HttpResponseMessage response;
            if (isPreflightRequest)
            {
                if (authorized)
                {
                    response = new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                {
                    response = request.CreateErrorResponse(HttpStatusCode.BadRequest, corsAttribute.ErrorMessage);
                }
            }
            else
            {
                response = base.SendAsync(request, cancellationToken).Result;
            }

            //添加响应报头
            if (headers != null && headers.Any())
                foreach (var item in headers)
                    response.Headers.Add(item.Key, item.Value);

            return Task.Factory.StartNew(() => response);
            //only .net4.5 supports Task.FromResult
            //return Task.FromResult<HttpResponseMessage>(response);
        }
开发者ID:codeice,项目名称:IFramework,代码行数:55,代码来源:CorsMessageHandler.cs

示例2: GetPerRequestFormatterInstance

        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
        {
            if (_viewLocator == null || _viewParser == null)
            {
                var config = request.GetConfiguration();

                if (config != null)
                {
                    IViewLocator viewLocator = null;
                    IViewParser viewParser = null;

                    var resolver = config.DependencyResolver;

                    if (_viewLocator == null)
                        viewLocator = (IViewLocator) resolver.GetService(typeof (IViewLocator));

                    if (_viewParser == null)
                        viewParser = (IViewParser) resolver.GetService(typeof (IViewParser));

                    return new HtmlMediaTypeViewFormatter(_siteRootPath, viewLocator, viewParser);
                }
            }

            return base.GetPerRequestFormatterInstance(type, request, mediaType);
        }
开发者ID:abhishekbhalani,项目名称:WebApiContrib.Formatting.Html,代码行数:25,代码来源:HtmlMediaTypeViewFormatter.cs

示例3: ContentFor

        private HttpContent ContentFor(HttpRequestMessage request, SwaggerDocument swaggerDoc)
        {
            var negotiator = request.GetConfiguration().Services.GetContentNegotiator();
            var result = negotiator.Negotiate(typeof(SwaggerDocument), request, GetSupportedSwaggerFormatters());

            return new ObjectContent(typeof(SwaggerDocument), swaggerDoc, result.Formatter, result.MediaType);
        }
开发者ID:spadger,项目名称:Swashbuckle,代码行数:7,代码来源:SwaggerDocsHandler.cs

示例4: SendAsync

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            Collection<IResponseEnricher> enrichers = request.GetConfiguration().GetResponseEnrichers();
            return enrichers.Where(e => e.CanEnrich(response))
                .Aggregate(response, (resp, enricher) => enricher.Enrich(response));
        }
开发者ID:mahf,项目名称:ASPNETWebAPISamples,代码行数:7,代码来源:EnrichingHandler.cs

示例5: SendAsync

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpConfiguration config = request.GetConfiguration();
            IHostPrincipalService principalService = config.Services.GetHostPrincipalService();
            IPrincipal principal = principalService.GetCurrentPrincipal(request);

            if (!principal.Identity.IsAuthenticated || !SuppressIfAlreadyAuthenticated)
            {
                if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == _httpBasicSchemeName)
                {
                    string username, password;
                    if (TryExtractBasicAuthCredentialsFromHeader(request.Headers.Authorization.Parameter, out username, out password))
                    {
                        IPrincipal returnedPrincipal = await AuthenticateUserAsync(request, username, password, cancellationToken);

                        // Check if the user has been authenticated successfully
                        if (returnedPrincipal != null)
                        {
                            principalService.SetCurrentPrincipal(returnedPrincipal, request);
                            return await base.SendAsync(request, cancellationToken);
                        }
                    }
                }
            }

            // Request is not authanticated. Handle unauthenticated request.
            return await HandleUnauthenticatedRequestImpl(request, cancellationToken);
        }
开发者ID:mahf,项目名称:ASPNETWebAPISamples,代码行数:28,代码来源:BasicAuthenticationHandler.cs

示例6: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Method == HttpMethod.Options)
            {
                var apiExplorer = request.GetConfiguration().Services.GetApiExplorer();

                var controllerRequested = request.GetRouteData().Values["controller"] as string;
                var supportedMethods = apiExplorer.ApiDescriptions
                    .Where(d =>
                    {
                        var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
                        return string.Equals(
                            controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
                    })
                    .Select(d => d.HttpMethod.Method)
                    .Distinct();

                if (!supportedMethods.Any())
                {
                    return Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
                }

                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Headers.Add("Access-Control-Allow-Origin", "*");
                response.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));

                return Task.FromResult(response);
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:benfoster,项目名称:ApiDogFood,代码行数:31,代码来源:CorsHandler.cs

示例7: ProcessBatchAsync

        /// <inheritdoc/>
        public override async Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            ValidateRequest(request);

            IList<ODataBatchRequestItem> subRequests = await ParseBatchRequestsAsync(request, cancellationToken);

            string preferHeader = RequestPreferenceHelpers.GetRequestPreferHeader(request);
            if ((preferHeader != null && preferHeader.Contains(PreferenceContinueOnError)) || (!request.GetConfiguration().HasEnabledContinueOnErrorHeader()))
            {
                ContinueOnError = true;
            }
            else
            {
                ContinueOnError = false;
            }

            try
            {
                IList<ODataBatchResponseItem> responses = await ExecuteRequestMessagesAsync(subRequests, cancellationToken);
                return await CreateResponseMessageAsync(responses, request, cancellationToken);
            }
            finally
            {
                foreach (ODataBatchRequestItem subRequest in subRequests)
                {
                    request.RegisterForDispose(subRequest.GetResourcesForDisposal());
                    request.RegisterForDispose(subRequest);
                }
            }
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:36,代码来源:DefaultODataBatchHandler.cs

示例8: GetCorsPolicyProvider

        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
            HttpActionDescriptor actionDescriptor = null;
            if (corsRequestContext.IsPreflight)
            {
                HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);

                request.RegisterForDispose(targetRequest);

                try
                {
                    foreach (var property in request.Properties)
                    {
                        // The RouteData and HttpContext from the preflight request properties contain information
                        // relevant to the preflight request and not the actual request, therefore we need to exclude them.
                        if (property.Key != HttpPropertyKeys.HttpRouteDataKey &&
                            property.Key != HttpContextBaseKey)
                        {
                            targetRequest.Properties.Add(property.Key, property.Value);
                        }
                    }

                    HttpConfiguration config = request.GetConfiguration();
                    if (config == null)
                    {
                        throw new InvalidOperationException(SRResources.NoConfiguration);
                    }

                    IHttpRouteData routeData = config.Routes.GetRouteData(request);
                    if (routeData == null)
                    {
                        // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
                        // and let the CorsMessageHandler flow the request to the normal Web API pipeline.
                        return null;
                    }

                    actionDescriptor = SelectAction(targetRequest, routeData, config);
                }
                catch
                {
                    if (DefaultPolicyProvider != null)
                    {
                        return DefaultPolicyProvider;
                    }
                    throw;
                }
            }
            else
            {
                actionDescriptor = request.GetActionDescriptor();
            }

            return GetCorsPolicyProvider(actionDescriptor);
        }
开发者ID:ahmetgoktas,项目名称:aspnetwebstack,代码行数:60,代码来源:AttributeBasedPolicyProviderFactory.cs

示例9: DefaultRootUrlResolver

 /// <summary>
 /// 
 /// </summary>
 /// <returns></returns>
 internal static string DefaultRootUrlResolver(HttpRequestMessage request)
 {
     string text = request.GetConfiguration().VirtualPathRoot.TrimEnd(new char[] { '/' });
     Uri requestUri = request.RequestUri;
     return string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}{3}", new object[]
     { 
         requestUri.Scheme, requestUri.Host, requestUri.Port, text 
     });
 }
开发者ID:sudarsanan-krishnan,项目名称:DynamicsCRMConnector,代码行数:13,代码来源:JsonSwaggerGenerator.cs

示例10: SelectController

 public HttpControllerDescriptor SelectController(HttpRequestMessage request)
 {
     // Uses the current State key to create the Web Api Controller Type
     return new HttpControllerDescriptor
     {
         Configuration = request.GetConfiguration(),
         ControllerType = Type.GetType("NavigationEdgeApi.Controllers." + request.Properties["key"] + "Controller", true, true)
     };
 }
开发者ID:grahammendick,项目名称:NavigationEdge,代码行数:9,代码来源:ControllerSelector.cs

示例11: HandleOptionsRequestAsync

        private async Task<HttpResponseMessage> HandleOptionsRequestAsync(HttpRequestMessage request)
        {
            var apis = GetMatchingApis(request.GetConfiguration().Routes, request).ToList();

            if (!apis.Any())
                return await Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));

            var supportedMethods = apis.Select(i => i.Method)
                                       .Distinct()
                                       .ToList();

            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            resp.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));

            var neg = request.GetConfiguration().Services.GetContentNegotiator();
            var res = neg.Negotiate(typeof (IEnumerable<SimpleApiDescription>), request, request.GetConfiguration().Formatters);
            resp.Content = new ObjectContent(typeof(IEnumerable<SimpleApiDescription>), apis, res.Formatter);
            
            return await Task.FromResult(resp);
        }
开发者ID:battenworks,项目名称:NuGet.Lucene,代码行数:20,代码来源:CrossOriginMessageHandler.cs

示例12: DefaultRootUrlResolver

        public static string DefaultRootUrlResolver(HttpRequestMessage request)
        {
            var scheme = GetHeaderValue(request, "X-Forwarded-Proto") ?? request.RequestUri.Scheme;
            var host = GetHeaderValue(request, "X-Forwarded-Host") ?? request.RequestUri.Host;
            var port = GetHeaderValue(request, "X-Forwarded-Port") ?? request.RequestUri.Port.ToString(CultureInfo.InvariantCulture);

            var httpConfiguration = request.GetConfiguration();
            var virtualPathRoot = httpConfiguration.VirtualPathRoot.TrimEnd('/');

            return string.Format("{0}://{1}:{2}{3}", scheme, host, port, virtualPathRoot);
        }
开发者ID:fly-bug,项目名称:aspnetboilerplate,代码行数:11,代码来源:SwaggerDocsConfig.cs

示例13: SendAsync

        /// <inheritdoc/>
        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            HttpConfiguration configuration = request.GetConfiguration();
            if (configuration == null)
            {
                throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
            }

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            // Do not interfere with null responses, we want to buble it up to the top.
            // Do not handle 204 responses as the spec says a 204 response must not include an ETag header
            // unless the request's representation data was saved without any transformation applied to the body
            // (i.e., the resource's new representation data is identical to the representation data received in the
            // PUT request) and the ETag value reflects the new representation.
            // Even in that case returning an ETag is optional and it requires access to the original object which is 
            // not possible with the current architecture, so if the user is interested he can set the ETag in that
            // case by himself on the response.
            if (response == null || !response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NoContent)
            {
                return response;
            }

            ODataPath path = request.ODataProperties().Path;
            IEdmModel model = request.ODataProperties().Model;

            IEdmEntityType edmType = GetSingleEntityEntityType(path);
            object value = GetSingleEntityObject(response);

            IEdmEntityTypeReference typeReference = GetTypeReference(model, edmType, value);
            if (typeReference != null)
            {
                EntityInstanceContext context = CreateInstanceContext(typeReference, value);
                context.EdmModel = model;
                context.NavigationSource = path.NavigationSource;
                IETagHandler etagHandler = configuration.GetETagHandler();
                EntityTagHeaderValue etag = CreateETag(context, etagHandler);

                if (etag != null)
                {
                    response.Headers.ETag = etag;
                }
            }

            return response;
        }
开发者ID:chinadragon0515,项目名称:WebApi,代码行数:54,代码来源:ETagMessageHandler.cs

示例14: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken)
                .ContinueWith(task =>
                {
                    var response = task.Result;
                    var enrichers = request.GetConfiguration().GetResponseEnrichers();

                    return enrichers.Where(e => e.CanEnrich(response))
                        .Aggregate(response, (resp, enricher) => enricher.Enrich(response));
                });
        }
开发者ID:ballrok,项目名称:Fabrik.Common,代码行数:12,代码来源:EnrichingHandler.cs

示例15: ConfigureFormatter

 /// <summary>
 /// Configure the JsonFormatter to only serialize the requested properties
 /// </summary>
 /// <param name="request"></param>
 /// <param name="includedTypeProperties"></param>
 private void ConfigureFormatter(HttpRequestMessage request, Dictionary<Type, List<string>> includedTypeProperties)
 {
     var jsonFormatter = request.GetConfiguration().Formatters.JsonFormatter;
     var settings = jsonFormatter.SerializerSettings;
     settings.Formatting = Formatting.Indented;
     //settings.Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
     //{
     //    logger.Error(args.ErrorContext.Error.Message);
     //    args.ErrorContext.Handled = true;
     //};
     settings.ContractResolver = new NHIncludingContractResolver(NHEagerFetch.sessionFactory, includedTypeProperties);
 }
开发者ID:Vintharas,项目名称:Breeze,代码行数:17,代码来源:BreezeNHQueryableAttribute.cs


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