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


C# Controllers.HttpControllerContext类代码示例

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


HttpControllerContext类属于System.Web.Http.Controllers命名空间,在下文中一共展示了HttpControllerContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RouteRequest

        public static RouteInfo RouteRequest(HttpConfiguration config, HttpRequestMessage request)
        {
            // create context
            var controllerContext = new HttpControllerContext(config, Substitute.For<IHttpRouteData>(), request);

            // get route data
            var routeData = config.Routes.GetRouteData(request);
            RemoveOptionalRoutingParameters(routeData.Values);

            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
            controllerContext.RouteData = routeData;

            // get controller type
            var controllerDescriptor = new DefaultHttpControllerSelector(config).SelectController(request);
            controllerContext.ControllerDescriptor = controllerDescriptor;

            // get action name
            var actionMapping = new ApiControllerActionSelector().SelectAction(controllerContext);

            return new RouteInfo
            {
                Controller = controllerDescriptor.ControllerType,
                Action = actionMapping.ActionName
            };
        }
开发者ID:vefve,项目名称:StreamusServer,代码行数:25,代码来源:Helpers.cs

示例2: TestRoute

        public void TestRoute(string url, string verb, Type type, string actionName)
        {
            //Arrange
            url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
            url = Host + url;

            //Act
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

            IHttpControllerSelector controller = this.GetControllerSelector();
            IHttpActionSelector action = this.GetActionSelector();

            IHttpRouteData route = this.Config.Routes.GetRouteData(request);
            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;

            HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);

            HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
            {
                ControllerDescriptor = controllerDescriptor
            };

            var actionDescriptor = action.SelectAction(context);

            //Assert
            Assert.NotNull(controllerDescriptor);
            Assert.NotNull(actionDescriptor);
            Assert.Equal(type, controllerDescriptor.ControllerType);
            Assert.Equal(actionName, actionDescriptor.ActionName);
        }
开发者ID:abinabrahamanchery,项目名称:mixerp,代码行数:31,代码来源:GetPartyTypeIdByPartyCodeRouteTests.cs

示例3: WrapperResolvesAuthenticationFilterFromDependencyScope

        public void WrapperResolvesAuthenticationFilterFromDependencyScope()
        {
            var builder = new ContainerBuilder();
            builder.Register<ILogger>(c => new Logger()).InstancePerDependency();
            var activationCount = 0;
            builder.Register<IAutofacAuthenticationFilter>(c => new TestAuthenticationFilter(c.Resolve<ILogger>()))
                .AsWebApiAuthenticationFilterFor<TestController>(c => c.Get())
                .InstancePerRequest()
                .OnActivated(e => activationCount++);
            var container = builder.Build();

            var resolver = new AutofacWebApiDependencyResolver(container);
            var configuration = new HttpConfiguration { DependencyResolver = resolver };
            var requestMessage = new HttpRequestMessage();
            requestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, configuration);
            var contollerContext = new HttpControllerContext { Request = requestMessage };
            var controllerDescriptor = new HttpControllerDescriptor { ControllerType = typeof(TestController) };
            var methodInfo = typeof(TestController).GetMethod("Get");
            var actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, methodInfo);
            var actionContext = new HttpActionContext(contollerContext, actionDescriptor);
            var context = new HttpAuthenticationContext(actionContext, Thread.CurrentPrincipal);
            var metadata = new FilterMetadata
            {
                ControllerType = typeof(TestController),
                FilterScope = FilterScope.Action,
                MethodInfo = methodInfo
            };
            var wrapper = new AuthenticationFilterWrapper(metadata);

            wrapper.OnAuthenticate(context);
            Assert.That(activationCount, Is.EqualTo(1));
        }
开发者ID:RoymanJing,项目名称:Autofac,代码行数:32,代码来源:AuthenticationFilterWrapperFixture.cs

示例4: GetClientContext

        /// <summary>
        /// Creates a ClientContext token for the incoming WebAPI request. This is done by 
        /// - looking up the servicesToken
        /// - extracting the cacheKey 
        /// - get the AccessToken from cache. If the AccessToken is expired a new one is requested using the refresh token
        /// - creation of a ClientContext object based on the AccessToken
        /// </summary>
        /// <param name="httpControllerContext">Information about the HTTP request that reached the WebAPI controller</param>
        /// <returns>A valid ClientContext object</returns>
        public static ClientContext GetClientContext(HttpControllerContext httpControllerContext)
        {
            if (httpControllerContext == null)
                throw new ArgumentNullException("httpControllerContext");

            string cacheKey = GetCacheKeyValue(httpControllerContext);

            if (!String.IsNullOrEmpty(cacheKey))
            {
                WebAPIContexCacheItem cacheItem = WebAPIContextCache.Instance.Get(cacheKey);

                //request a new access token from ACS whenever our current access token will expire in less than 1 hour
                if (cacheItem.AccessToken.ExpiresOn < (DateTime.Now.AddHours(-1)))
                {
                    Uri targetUri = new Uri(cacheItem.SharePointServiceContext.HostWebUrl);
                    OAuth2AccessTokenResponse accessToken = TokenHelper.GetAccessToken(cacheItem.RefreshToken, TokenHelper.SharePointPrincipal, targetUri.Authority, TokenHelper.GetRealmFromTargetUrl(targetUri));
                    cacheItem.AccessToken = accessToken;
                    //update the cache
                    WebAPIContextCache.Instance.Put(cacheKey, cacheItem);
                    LoggingUtility.Internal.TraceInformation((int)EventId.ServicesTokenRefreshed, CoreResources.Services_TokenRefreshed, cacheKey, cacheItem.SharePointServiceContext.HostWebUrl);
                }
                 
                return TokenHelper.GetClientContextWithAccessToken(cacheItem.SharePointServiceContext.HostWebUrl, cacheItem.AccessToken.AccessToken);
            }
            else
            {
                LoggingUtility.Internal.TraceWarning((int)EventId.ServicesNoCachedItem, CoreResources.Services_CookieWithCachKeyNotFound);
                throw new Exception("The cookie with the cachekey was not found...nothing can be retrieved from cache, so no clientcontext can be created.");
            }            
        }
开发者ID:AaronSaikovski,项目名称:PnP,代码行数:39,代码来源:WebAPIHelper.cs

示例5: ExecuteActualRequest

        private async Task<HttpResponseMessage> ExecuteActualRequest(HttpControllerContext controllerContext, CancellationToken cancellationToken,
            MixedModeRequestAuthorizer authorizer)
        {
            if (SkipAuthorizationSinceThisIsMultiGetRequestAlreadyAuthorized == false)
            {
                HttpResponseMessage authMsg;
                if (authorizer.TryAuthorize(this, out authMsg) == false)
                    return authMsg;
            }

            if (IsInternalRequest == false)
                RequestManager.IncrementRequestCount();

            if (DatabaseName != null && await DatabasesLandlord.GetDatabaseInternal(DatabaseName) == null)
            {
                var msg = "Could not find a database named: " + DatabaseName;
                return GetMessageWithObject(new { Error = msg }, HttpStatusCode.ServiceUnavailable);
            }

            var sp = Stopwatch.StartNew();

            var result = await base.ExecuteAsync(controllerContext, cancellationToken);
            sp.Stop();
            AddRavenHeader(result, sp);

            return result;
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:27,代码来源:RavenDbApiController.cs

示例6: SelectAction

        /// <summary>
        /// This class is called by Web API system to select action method from given controller.
        /// </summary>
        /// <param name="controllerContext">Controller context</param>
        /// <returns>Action to be used</returns>
        public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            //TODO: If method is not supplied, try to guess the method by Http Verb and parameters ?

            object controllerInfoObj;
            if (controllerContext.ControllerDescriptor.Properties.TryGetValue("__AbpDynamicApiControllerInfo", out  controllerInfoObj))
            {
                //Get controller information which is selected by AbpHttpControllerSelector.
                var controllerInfo = controllerInfoObj as DynamicApiControllerInfo;
                if (controllerInfo == null)
                {
                    throw new AbpException("__AbpDynamicApiControllerInfo in ControllerDescriptor.Properties is not a " + typeof(DynamicApiControllerInfo).FullName + " class.");
                }

                //Get action name
                var actionName = (controllerContext.RouteData.Values["action"] as string);
                if (string.IsNullOrWhiteSpace(actionName))
                {
                    throw new AbpException("There is no action specified.");
                }

                //Get action information
                actionName = (controllerContext.RouteData.Values["action"] as string).ToPascalCase();
                if (!controllerInfo.Actions.ContainsKey(actionName))
                {
                    throw new AbpException("There is no action " + actionName + " defined for api controller " + controllerInfo.Name);
                }

                return new DyanamicHttpActionDescriptor(controllerContext.ControllerDescriptor, controllerInfo.Actions[actionName].Method);
            }

            return base.SelectAction(controllerContext);
        }
开发者ID:khachatur,项目名称:aspnetboilerplate,代码行数:38,代码来源:AbpApiControllerActionSelector.cs

示例7: CreateActionContext

 public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)
 {
     HttpControllerContext context = controllerContext ?? CreateControllerContext();
     HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor();
     descriptor.ControllerDescriptor = context.ControllerDescriptor;
     return new HttpActionContext(context, descriptor);
 }
开发者ID:nazhir,项目名称:kawaldesa,代码行数:7,代码来源:ContextUtils.cs

示例8: ExecuteAsync

        /// <summary>
        /// 通过表达式执行方法,具体在 ReflectedHttpActionDescriptor 中实现
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="arguments"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override System.Threading.Tasks.Task<object> ExecuteAsync(HttpControllerContext controllerContext, System.Collections.Generic.IDictionary<string, object> arguments, System.Threading.CancellationToken cancellationToken)
        {
            dynamic generic = controllerContext.Controller;

            var applicationService = generic.ApplicationService;
            controllerContext.Controller = controllerContext.Controller = applicationService;
            return base
                .ExecuteAsync(controllerContext, arguments, cancellationToken)
                .ContinueWith(task =>
                {
                    try
                    {
                        if (task.Result == null)
                        {

                            return new AjaxResponse();
                        }

                        if (task.Result is AjaxResponse)
                        {
                            return task.Result;
                        }

                        return new AjaxResponse(task.Result);
                    }
                    catch (Exception ex)
                    {

                        throw ex;
                    }
                }, cancellationToken);
        }
开发者ID:dingsongjie,项目名称:LancheProject,代码行数:39,代码来源:DynamicHttpActionDescriptor.cs

示例9: Id_Invalid_string_Should_Return_BadRequest

        public void Id_Invalid_string_Should_Return_BadRequest()
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/post");
            request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

            var httpControllerContext = new HttpControllerContext {
                 Request = request
            };

            var httpActionContext = new HttpActionContext {
                ControllerContext = httpControllerContext
            };

            httpActionContext.ModelState.AddModelError("id", "string is not a int");

            // Testing filter
            var filter = new ModelValidationFilterBase();
            filter.OnActionExecuting(httpActionContext);

            filter = new IdValidationFilterAttribute();
            filter.OnActionExecuting(httpActionContext);

            Assert.IsFalse(httpActionContext.ModelState.IsValid);
            Assert.IsTrue(httpActionContext.Response.StatusCode == HttpStatusCode.BadRequest);
            Assert.IsTrue(((Dictionary<string, IEnumerable<string>>) ((ObjectContent) (httpActionContext.Response.Content)).Value)["id"].FirstOrDefault() == "string is not a int");
        }
开发者ID:edgardojimenez,项目名称:mobws,代码行数:26,代码来源:IdValidationFilterAttributeTest.cs

示例10: ProcessRequestContentHeader

        protected virtual ReflectedHttpActionDescriptor ProcessRequestContentHeader(HttpControllerContext context,
                                   IEnumerable<ReflectedHttpActionDescriptor> actionDescriptors)
        {
            // normally for POST and PUT that we resolve with content type
            if (context.Request.Content != null && context.Request.Content.Headers.ContentType != null)
            {
                var extendedMedaType = context.Request.Content.Headers.ContentType.ExtractFiveLevelsOfMediaType();
                if (extendedMedaType != null)
                {
                    var candidate = actionDescriptors.FirstOrDefault(x =>
                                                                     x.MethodInfo.GetParameters()
                                                                      .Any(p =>
                                                                           p.ParameterType.Name
                                                                            .Equals(
                                                                                _domainNameToTypeNameMapper(extendedMedaType.DomainModel),
                                                                                StringComparison
                                                                                    .CurrentCultureIgnoreCase)));
                    if (candidate != null)
                        return candidate;
                };

            }

            return null;
        }
开发者ID:modulexcite,项目名称:FiveLevelsOfMediaType,代码行数:25,代码来源:MediaTypeBasedActionSelector.cs

示例11: SelectAction

        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            var controllerType = controllerContext.ControllerDescriptor.ControllerType;

            if (typeof(CustomersController) == controllerType)
            {
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET
                {
                    controllerContext.RouteData.Values["orderID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
            }
            else if (typeof(OrdersController) == controllerType)
            {
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET
                {
                    controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation/key")) //PATCH OR DELETE
                {
                    controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;

                    controllerContext.RouteData.Values["key"] = ((KeySegment)odataPath.Segments[3]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
            }

            return base.SelectAction(odataPath, controllerContext, actionMap);
        }
开发者ID:rbeauchamp,项目名称:Swashbuckle.OData,代码行数:30,代码来源:CustomNavigationPropertyRoutingConvention.cs

示例12: ProcessAcceptHeader

        protected virtual ReflectedHttpActionDescriptor ProcessAcceptHeader(HttpControllerContext context,
                                                                              IEnumerable<ReflectedHttpActionDescriptor>
                                                                                  actionDescriptors)
        {
            // GET calls that can be resolved by Accept which has a Non-Canonical Media Type
            // only if it is the first item in Accept Header
            // use of 5LMT header parameters also supported
            if (context.Request.Method.Method == "GET" && context.Request.Headers.Accept.Count > 0)
            {
                var extendedMediaType = context.Request.Headers.Accept.First()
                    .ExtractFiveLevelsOfMediaType(FiveLevelsOfMediaTypeFormatter.DefaultNonCanonicalMediaTypePattern);

                if (extendedMediaType != null && !string.IsNullOrEmpty(extendedMediaType.DomainModel))
                {
                    var matches = actionDescriptors.Where(x => x.MethodInfo.ReturnType.Name ==
                        _domainNameToTypeNameMapper(extendedMediaType.DomainModel)).ToArray();

                    if (matches.Length == 1)
                        return matches.First();

                    if (matches.Length > 1)
                    {

                        var theMatchBasedOnVersion = matches.FirstOrDefault(x => _versionChecker(x, extendedMediaType.Version));
                        if (theMatchBasedOnVersion != null)
                            return theMatchBasedOnVersion;
                    }
                }
            }

            return null;
        }
开发者ID:modulexcite,项目名称:FiveLevelsOfMediaType,代码行数:32,代码来源:MediaTypeBasedActionSelector.cs

示例13: Initialize

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            var hub = ((IHub)this);

            var hubName = this.GetType().FullName;
            var hubManager = _resolver.Resolve<IHubManager>();
            var descriptor = hubManager.EnsureHub(hubName);

            var user = controllerContext.Request.GetUserPrincipal();

            // Response parameter is null here because outgoing broadcast messages will always go
            // via the SignalR intrinsics, and method return values via the Web API intrinsics.
            var hostContext = new HostContext(new WebApiRequest(controllerContext.Request), null, user);
            var connectionId = hostContext.Request.QueryString["connectionId"];
            hub.Context = new HubContext(hostContext, connectionId);

            var connection = _resolver.Resolve<IConnectionManager>().GetConnection<HubDispatcher>();
            var state = new TrackingDictionary();
            var agent = new ClientAgent(connection, descriptor.Name);
            hub.Caller = new SignalAgent(connection, connectionId, descriptor.Name, state);
            hub.Agent = agent;
            hub.GroupManager = agent;

            base.Initialize(controllerContext);
        }
开发者ID:daodao10,项目名称:SignalR.WebApi,代码行数:25,代码来源:ConnectedApiController.cs

示例14: SelectAction

        public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            var action = base.SelectAction(controllerContext);

            if (!controllerContext.Request.IsCurrentUserBetaTester() || DateTime.Now.Second % 2 == 0)
            {
                // Send the user to the 'normal' action
                return action;
            }
            else
            {
                // This user is in the beta program and was selected to see a different version of the action.

                HttpActionDescriptor betaAction;
                if (!_betaActions.TryGetValue(action, out betaAction))
                {
                    betaAction = CreateBetaAction(action);
                    _betaActions.TryAdd(action, betaAction);
                }

                if (betaAction == null)
                {
                    return action;
                }
                else
                {
                    return betaAction;
                }
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:30,代码来源:BetaTestingActionSelector.cs

示例15: GetHttpRouteHelper

        private static string GetHttpRouteHelper(HttpControllerContext controllerContext, string routeName, IDictionary<string, object> routeValues)
        {
            if (routeValues == null)
            {
                // If no route values were passed in at all we have to create a new dictionary
                // so that we can add the extra "httproute" key.
                routeValues = new Dictionary<string, object>();
                routeValues.Add(HttpRoute.HttpRouteKey, true);
            }
            else
            {
                if (!routeValues.ContainsKey(HttpRoute.HttpRouteKey))
                {
                    // Copy the dictionary so that we can add the extra "httproute" key used by all Web API routes to
                    // disambiguate them from other MVC routes.
                    routeValues = new Dictionary<string, object>(routeValues);
                    routeValues.Add(HttpRoute.HttpRouteKey, true);
                }
            }

            IHttpVirtualPathData vpd = controllerContext.Configuration.Routes.GetVirtualPath(
                controllerContext: controllerContext,
                name: routeName,
                values: routeValues);
            if (vpd == null)
            {
                return null;
            }
            return vpd.VirtualPath;
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:30,代码来源:UrlHelper.cs


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