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

C# Controllers.HttpControllerContext类代码示例

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

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



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


示例16: ExecuteBindingAsync_CallsGetPerRequestFormatterInstance_BeforeBinding

        public void ExecuteBindingAsync_CallsGetPerRequestFormatterInstance_BeforeBinding()
        {
            // Arrange
            Mock<HttpParameterDescriptor> parameter = new Mock<HttpParameterDescriptor>();
            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>();
            MediaTypeFormatter perRequestFormatter = new Mock<MediaTypeFormatter>().Object;

            MockPerRequestParameterBinding binding = new MockPerRequestParameterBinding(parameter.Object, new[] { formatter.Object });

            HttpRequestMessage request = new HttpRequestMessage();
            request.Content = new StringContent("{}");
            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/something");
            HttpControllerContext controllercontext = new HttpControllerContext { Request = request };
            HttpActionContext actionContext = new HttpActionContext(controllercontext, new Mock<HttpActionDescriptor>().Object);

            MediaTypeFormatter formatterUsedForPrameterBinding = null;
            binding.CreateInnerBindingFunc = (formatters) =>
                {
                    formatterUsedForPrameterBinding = formatters.Single();
                    return new VoidParameterBinding();
                };

            formatter
                .Setup(f => f.GetPerRequestFormatterInstance(parameter.Object.ParameterType, request, request.Content.Headers.ContentType))
                .Returns(perRequestFormatter);

            // Act
            binding.ExecuteBindingAsync(new Mock<ModelMetadataProvider>().Object, actionContext, new CancellationToken());

            // Assert
            Assert.Same(formatterUsedForPrameterBinding, perRequestFormatter);
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:32,代码来源:PerRequestParameterBindingTest.cs


示例17: Initialize

 protected override void Initialize(HttpControllerContext controllerContext)
 {
     base.Initialize(controllerContext);
     storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
     var tableClient = storageAccount.CreateCloudTableClient();
     table = tableClient.GetTableReference("people");
 }
开发者ID:cmpcdaly,项目名称:table-storage-web-api-cache,代码行数:7,代码来源:PersonController.cs


示例18: ExecuteAsync

        public Task<HttpResponseMessage> ExecuteAsync(
            HttpControllerContext controllerContext, 
            CancellationToken cancellationToken) {

            var request = controllerContext.Request;

            if (request.Method == HttpMethod.Get) {

                var cars = new[] { "Car 1", "Car 2", "Car 3" };
                var response = request.CreateResponse(HttpStatusCode.OK, cars);

                //.NET v4.0 with TaskHelpers.Sources package
                //return TaskHelpers.FromResult(response);

                //.NET v4.5
                return Task.FromResult(response);
            }

            //.NET v4.0 with TaskHelpers.Sources package
            //return TaskHelpers.FromResult(
            //      request.CreateResponse(HttpStatusCode.MethodNotAllowed));

            //.NET v4.5
            return Task.FromResult(
                request.CreateResponse(HttpStatusCode.MethodNotAllowed));

        }
开发者ID:mahf,项目名称:ASPNETWebAPISamples,代码行数:27,代码来源:CarsController.cs


示例19: 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)
        {
            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 Exception("__AbpDynamicApiControllerInfo in ControllerDescriptor.Properties is not a " + typeof(DynamicApiControllerInfo).FullName + " class.");
                }

                //Get action name
                var serviceNameWithAction = (controllerContext.RouteData.Values["serviceNameWithAction"] as string);
                if (serviceNameWithAction != null)
                {
                    var actionName = DynamicApiServiceNameHelper.GetActionNameInServiceNameWithAction(serviceNameWithAction);

                    //Get action information
                    if (!controllerInfo.Actions.ContainsKey(actionName))
                    {
                        throw new Exception("There is no action " + actionName + " defined for api controller " + controllerInfo.ServiceName);
                    }

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

            return base.SelectAction(controllerContext);
        }
开发者ID:mlkj,项目名称:20151010YL,代码行数:35,代码来源:YLApiControllerActionSelectorTemp.cs


示例20: SelectAction

        /// <summary>
        /// Selects the action for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionMap">The action map.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected action
        /// </returns>
        public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            if (odataPath.PathTemplate == "~")
            {
                return "GetServiceDocument";
            }

            if (odataPath.PathTemplate == "~/$metadata")
            {
                return "GetMetadata";
            }

            return null;
        }
开发者ID:tlycken,项目名称:aspnetwebstack,代码行数:38,代码来源:MetadataRoutingConvention.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Controllers.HttpControllerSettings类代码示例发布时间:2022-05-26
下一篇:
C# Controllers.HttpActionContext类代码示例发布时间: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