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


C# HttpRequestMessage.GetRouteData方法代码示例

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


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

示例1: GetPerRequestFormatterInstance

        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request,MediaTypeHeaderValue mediaType)
        {
            //所需的对象属性
            var includingFields = request.GetRouteData().Values["fields"];
            if (includingFields != null && !string.IsNullOrEmpty(includingFields.ToString()))
            {
                FieldsJsonMediaTypeFormatter frmtr = new FieldsJsonMediaTypeFormatter();
                frmtr.CurrentRequest = request;
                var resolve = new Share.IncludableSerializerContractResolver(this.SerializerSettings.ContractResolver as Share.IgnorableSerializerContractResolver);
                //type.IsAssignableFrom(typeof(IEnumerable<Model.dr_pre_visit>))
                if (type.GetInterface("IEnumerable") != null)
                {
                    resolve.Include(type.GenericTypeArguments[0], includingFields.ToString(), ',');
                }
                else
                {
                    resolve.Include(type, includingFields.ToString(), ",");
                }

                frmtr.SerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = resolve,
                };
                return frmtr;
            }
            else
            {
                return this;
            }
        }
开发者ID:lehprject,项目名称:sfjyDMS,代码行数:30,代码来源:FieldsJsonMediaTypeFormatter.cs

示例2: SendAsync

        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var resource = ((string)request.GetRouteData().Values["controller"]).ToLower();
            var action = request.GetRouteData().Values.ContainsKey("action") ? ((string)request.GetRouteData().Values["action"]).ToLower() : null;
            var method = request.Method.ToString().ToUpper();

            var securityToken = GetToken(request);
            try
            {
                _authenticationService.ValidateAccess(securityToken, resource, action, method);
            }
            catch (UnauthorizedException ex)
            {
                return request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
            }

            SaveContext(request, _authenticationService);

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

            UpdateContext(request, _authenticationService);

            securityToken = _authenticationService.CreateToken();

            if (securityToken != null)
                AddTokenToHeader(response, securityToken);

            return response;
        }
开发者ID:leocosta,项目名称:TicketStore,代码行数:29,代码来源:TokenValidationHandler.cs

示例3: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var setting = Its.Configuration.Settings.Get<Config.SwaggerToolSettings>();
            //using refletions to internal
            var swaggerProvider = (ISwaggerProvider)_config.GetType().GetMethod("GetSwaggerProvider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });

            var rootUrl = (string)_config.GetType().GetMethod("GetRootUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(_config, new object[] { request });
            var q = request.GetRouteData().Values["q"].ToString();
            var apiVersion = request.GetRouteData().Values["apiVersion"].ToString();

            try
            {
                var swaggerDoc = swaggerProvider.GetSwagger(rootUrl, apiVersion);

                //筛选条件为path包含q
                IList<string> keytoremove = new List<string>();
                foreach (var item in swaggerDoc.paths)
                {
                    if (!item.Key.ToUpper().Contains(q.ToUpper()))
                    {
                        keytoremove.Add(item.Key);
                    }
                }
                foreach (var item in keytoremove)
                {
                    swaggerDoc.paths.Remove(item);
                }
                var content = ContentFor(request, swaggerDoc);
                return TaskFor(new HttpResponseMessage { Content = content });
            }
            catch (UnknownApiVersion ex)
            {
                return TaskFor(request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }
        }
开发者ID:yuzukwok,项目名称:Abp.Web.Api.SwaggerTool,代码行数:35,代码来源:SwaggerSearchHandler.cs

示例4: GetHttpActionDescriptorForRestierController

        private static HttpActionDescriptor GetHttpActionDescriptorForRestierController(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor)
        {
            HttpActionDescriptor actionDescriptor;

            var perControllerConfig = controllerDescriptor.Configuration;
            request.SetConfiguration(perControllerConfig);
            var requestContext = request.GetRequestContext();
            requestContext.Configuration = perControllerConfig;
            requestContext.RouteData = request.GetRouteData();
            requestContext.Url = new UrlHelper(request);
            requestContext.VirtualPathRoot = perControllerConfig.VirtualPathRoot;

            var controller = controllerDescriptor.CreateController(request);

            using (controller as IDisposable)
            {
                var controllerContext = new HttpControllerContext(requestContext, request, controllerDescriptor, controller);
                try
                {
                    actionDescriptor = perControllerConfig.Services.GetActionSelector().SelectAction(controllerContext);
                }
                catch (HttpResponseException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound || ex.Response.StatusCode == HttpStatusCode.MethodNotAllowed)
                    {
                        actionDescriptor = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            return actionDescriptor;
        }
开发者ID:bigred8982,项目名称:Swashbuckle.OData,代码行数:35,代码来源:HttpRequestMessageExtensions.cs

示例5: SelectController

        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            var controllers = GetControllerMapping();

            var routeData = request.GetRouteData();

            var controllerName = routeData.Values["controller"].ToString();

            HttpControllerDescriptor descriptor;

            if (controllers.TryGetValue(controllerName, out descriptor))
            {
                //var version = "2";
                //var version = GetVersionFromQueryString(request);
                //var version = GetVersionFromHeader(request);
                //var version = GetVersionFromAcceptHeaderVersion(request);
                var version = GetVersionFromMediaType(request);

                var newName = string.Concat(controllerName, "V", version);

                HttpControllerDescriptor versionedDescriptor;

                if (controllers.TryGetValue(newName, out versionedDescriptor))
                {
                    return versionedDescriptor;
                }

                return descriptor;
            }
            return null;

            //return base.SelectController(request);
        }
开发者ID:vadpetrov,项目名称:Pluralsight,代码行数:33,代码来源:RCControllerSelector_v1.cs

示例6: GetLinkedRoutePatterns

        /// <summary>
        /// This method must be set to LinkedRoutePatternProvider of CachingHandler
        /// </summary>
        /// <param name="message"></param>
        /// <returns>All linked route patterns</returns>
        public virtual IEnumerable<string> GetLinkedRoutePatterns(HttpRequestMessage request)
        {
            var routeData = request.GetRouteData();
            if (routeData == null)
                return new string[0];

            var routeInfo = new RouteInfo(routeData.Route);

            // deal with no parameters
            if (routeInfo.Parameters.Count == 0)
                return new string[0];

            // deal with catchall
            if (routeInfo.Parameters.Any(x => x.IsCatchAll))
                return new string[0];

            var linkedRoutePatterns = new List<string>();
            linkedRoutePatterns.Add(routeInfo.GetRoot(routeData));

            if (!routeInfo.IsCollection(routeData))
            {
                linkedRoutePatterns.Add(routeInfo.BuildCollectionPattern(routeData));
            }

            return linkedRoutePatterns;

        }
开发者ID:yyf919,项目名称:CacheCow,代码行数:32,代码来源:ConventionalRoutePatternProvider.cs

示例7: GenerateLinksForTopic

        private static Topic GenerateLinksForTopic(Topic topic, HttpRequestMessage request)
        {
            var routeData = request.GetRouteData();
            var controller = routeData.Values["controller"];
            var urlHelper = request.GetUrlHelper();

            topic.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, id = topic.Id }), UriKind.Relative);

            if (topic.Comments != null && topic.Comments.Count > 0)
            {
                topic.Comments = new List<Comment>(topic.Comments.Select((cmt) =>
                {
                    cmt.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, id = cmt.Id }), UriKind.Relative);
                    cmt.TopicLink = new Uri(urlHelper.Route("DefaultApi", new { controller = "topics", id = cmt.TopicId }), UriKind.Relative);

                    return cmt;
                }));
            }

            if (topic.Tags != null && topic.Tags.Count > 0)
            {
                topic.Tags = new List<Tag>(topic.Tags.Select((tag) =>
                {
                    tag.SelfLink = new Uri(urlHelper.Route("DefaultApi", new { controller = controller, tags = tag.Name }), UriKind.Relative);
                    return tag;
                }));
            }

            return topic;
        }
开发者ID:seattlekiran,项目名称:TopicDiscusser,代码行数:30,代码来源:LinkGenerationHandler.cs

示例8: SelectController

        public HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            IHttpRouteData routeData = request.GetRouteData();
            if (routeData == null)
            {
                return _innerSelector.SelectController(request);
            }

            ODataPath odataPath = request.GetODataPath();
            if (odataPath == null)
            {
                return _innerSelector.SelectController(request);
            }

            foreach (IODataRoutingConvention routingConvention in _routingConventions)
            {
                string controllerName = routingConvention.SelectController(odataPath, request);
                if (controllerName != null)
                {
                    routeData.Values.Add(ODataRouteConstants.Controller, controllerName);
                    return _innerSelector.SelectController(request);
                }
            }

            throw new HttpResponseException(request.CreateErrorResponse(
                HttpStatusCode.NotFound,
                Error.Format(SRResources.NoMatchingResource, request.RequestUri),
                Error.Format(SRResources.NoRoutingHandlerToSelectController, odataPath.PathTemplate)));
        }
开发者ID:Swethach,项目名称:aspnetwebstack,代码行数:34,代码来源:ODataControllerSelector.cs

示例9: GetControllerFullName

        public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName)
        {
            object namespaceName;

            var data = request.GetRouteData();

            IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key,

                    t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList();

            if (data.Route.DataTokens == null ||

                !data.Route.DataTokens.TryGetValue(NamespaceRouteVariableName, out namespaceName))
            {

                return from k in keys

                       where k.EndsWith(string.Format(".{0}{1}", controllerName, DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase)

                       select k;

            }

            //get the defined namespace

            string[] namespaces = (string[])namespaceName;

            return from n in namespaces

                   join k in keys on string.Format("{0}.{1}{2}", n, controllerName, DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower()

                   select k;
        }
开发者ID:chenboyi081,项目名称:webapiVersionControll,代码行数:33,代码来源:NamespaceHttpControllerSelector.cs

示例10: GetControllerIdentificationFromRequest

        protected override ControllerIdentification GetControllerIdentificationFromRequest(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            IHttpRouteData routeData = request.GetRouteData();
            if (routeData == null)
            {
                return default(ControllerIdentification);
            }

            // Look up controller in route data
            string controllerName = this.GetControllerNameFromRequest(request);

            // Also try the version if possible
            object apiVersionObj;
            string apiVersion = null;
            //string version;
            //if (routeData.Values.TryGetValue(VersionKey, out apiVersionObj) &&
            //    Int32.TryParse(apiVersionObj.ToString(), out version))
            //{
            //    apiVersion = version;
            //}

            if (routeData.Values.TryGetValue(VersionKey, out apiVersionObj) && !string.IsNullOrWhiteSpace(apiVersionObj.ToString()))
            {
                apiVersion = apiVersionObj.ToString().Replace(".", "_");
            }

            return new ControllerIdentification(controllerName, apiVersion);
        }
开发者ID:rmjohn08,项目名称:IttWebApi,代码行数:33,代码来源:RouteVersionedControllerSelector.cs

示例11: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            StringBuilder sb = new StringBuilder("/");
            if (!string.IsNullOrEmpty(subdir))
            {
                sb.AppendFormat("{0}/", subdir);
            }
            sb.Append("Default.cshtml");

            var routeData = request.GetRouteData();
            if (routeData != null && routeData.Values.Count > 0)
            {
                sb.Append("?");
                foreach (var r in routeData.Values)
                {
                    sb.AppendFormat("{0}={1}&", r.Key, r.Value);
                }
                sb.Remove(sb.Length - 1, 1);
            }
            var url = request.RequestUri.AbsoluteUri;
            url = url.Replace(request.RequestUri.AbsolutePath, sb.ToString());

            request.RequestUri = new Uri(url);
            if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Options)
                request.Content = null;

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:cairabbit,项目名称:daf,代码行数:28,代码来源:CmsMessageHandler.cs

示例12: 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

示例13: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Lookup route data, or if not found as a request property then we look it up in the route table
            IHttpRouteData routeData = request.GetRouteData();
            if (routeData == null)
            {
                routeData = _configuration.Routes.GetRouteData(request);

                if (routeData != null)
                {
                    request.SetRouteData(routeData);
                }
                else
                {
                    request.Properties.Add(HttpPropertyKeys.NoRouteMatched, true);
                    return TaskHelpers.FromResult(request.CreateErrorResponse(
                        HttpStatusCode.NotFound,
                        Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                        SRResources.NoRouteData));
                }
            }

            routeData.RemoveOptionalRoutingParameters();

            // routeData.Route could be null if user adds a custom route that derives from System.Web.Routing.Route explicitly 
            // and add that to the RouteCollection in the web hosted case
            var invoker = (routeData.Route == null || routeData.Route.Handler == null) ?
                _defaultInvoker : new HttpMessageInvoker(routeData.Route.Handler, disposeHandler: false);
            return invoker.SendAsync(request, cancellationToken);
        }       
开发者ID:kiran2013,项目名称:aspnetwebstack,代码行数:30,代码来源:HttpRoutingDispatcher.cs

示例14: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            IHttpRouteData routeData = request.GetRouteData();
            int key;
            if(!int.TryParse(routeData.Values["customerkey"].ToString(), out key)) {

                return Task.FromResult(
                    request.CreateResponse(HttpStatusCode.NotFound)
                );
            }

            var dependecyScope = request.GetDependencyScope();
            var customerRepo = (IEntityRepository<Customer>)dependecyScope.GetService(typeof(IEntityRepository<Customer>));
            var customer = customerRepo.GetSingle(key);
            if (customer == null) {

                return Task.FromResult(
                    request.CreateResponse(HttpStatusCode.NotFound)
                );
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:tugberkugurlu,项目名称:AdvancedWebAPI,代码行数:25,代码来源:CustomerOrdersDispatcher.cs

示例15: SelectController

        //[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller is responsible for disposing of response instance.")]
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            //if (request == null)
            //{
            //    throw Error.ArgumentNull("request");
            //}
            //request.


            var version = GetVersionFromMediaType(request);

            IHttpRouteData routeData = request.GetRouteData();
            var a = routeData.GetDirectRouteCandidates();
            HttpControllerDescriptor controllerDescriptor;
            if (routeData != null)
            {
                controllerDescriptor = GetVersionedRouteController(routeData, version);
                if (controllerDescriptor != null)
                {
                    return controllerDescriptor;
                }
            }

           // var routeTemplate = routeData.Route.RouteTemplate;

            return null;

            
        }
开发者ID:Microshaoft,项目名称:Microshaoft.Common.Utilities.Net.4x,代码行数:30,代码来源:WebApiVersionedControllerSelector.cs


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