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


C# HttpRequestMessage.GetDependencyScope方法代码示例

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


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

示例1: SendAsync

        /// <summary>
        /// Web API custom message handler that verifies whether or not a pool exists in the persistence store that has a pool id included in a request URI.  If a pool with the id does not exist, an HTTP status code of "Not Found" is returned.
        /// </summary>
        /// <param name="request">HTTP request message.</param>
        /// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
        /// <returns>Task representing an asynchronous invocation of the message being sent.</returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", "request cannot be null.");
            }

            if (cancellationToken == null)
            {
                throw new ArgumentNullException("cancellationToken", "cancellationToken cannot be null.");
            }

            ////Verify that pool exists in persistence store.
            ////TODO: When creating route constraint, be sure to constrain value to int.
            int poolId = Convert.ToInt32(request.GetRouteData().Values["poolId"]);
            IPoolRepository poolRepository = (IPoolRepository)request.GetDependencyScope().GetService(typeof(IPoolRepository));

            ////Retrieve pool entity from persistence store.
            Pool poolToCheckExists = poolRepository.GetById(poolId);

            ////If pool does not exist in persistence store, return HTTP status code of "Not Found"
            ////NOTE: This return value is left intentionally vague so a potential hacker does not know what is missing from the URI.
            if (poolToCheckExists == null)
            {
                Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:swbyam,项目名称:footballpool,代码行数:35,代码来源:PoolExistsMessageHandler.cs

示例2: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_lockManager == null)
            {
                //http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/
                _lockManager = request.GetDependencyScope().GetService(typeof(ILockManager)) as ILockManager;
            }
            // Preconditions
            HttpResponseMessage error;
            if (!TryNoLockTokenMatchesRequestUri(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }

            if (!TryNoLockTokenSubmitted(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }

            if (!TryNoConflictingLock(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }
            return base.SendAsync(request, cancellationToken);
        }
开发者ID:keithb-,项目名称:Valley,代码行数:28,代码来源:LockDelegatingHandler.cs

示例3: SendAsync

 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     var scope = request.GetDependencyScope();
     var currentRequest = (CurrentRequest)scope.GetService(typeof(CurrentRequest));
     currentRequest.Value = request;
     return base.SendAsync(request, cancellationToken);
 }
开发者ID:hid-shibayama,项目名称:drum,代码行数:7,代码来源:InjectionUsingUnity.cs

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

示例5: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (accountService == null)
                accountService = request.GetDependencyScope().GetService(typeof (IAccountService)) as IAccountService;

            var headers = request.Headers;

            if(headers.Authorization == null || headers.Authorization.Scheme != Scheme)
                return base.SendAsync(request, cancellationToken);

            var values = Encoding.ASCII.GetString(Convert.FromBase64String(headers.Authorization.Parameter)).Split(':');
            string userName = values[0].Trim();
            string password = values[1].Trim();
            //var account = accountService.Get(userName, password);

            //if (account == null)
            //    return base.SendAsync(request, cancellationToken);

            //var principal = new GenericPrincipal(new GenericIdentity(userName),
            //                                        new[] {((RoleType) account.RoleType).ToString()});

            var principal = new GenericPrincipal(new GenericIdentity(userName),
                                                    new[] {"Admin"});

            Thread.CurrentPrincipal = principal;
            request.Properties.Add("user", principal);

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:antonmaju,项目名称:egg-farm-system,代码行数:29,代码来源:BasicAuthHandler.cs

示例6: Create

 public IHttpController Create(
     HttpRequestMessage request,
     HttpControllerDescriptor controllerDescriptor,
     Type controllerType)
 {
     var scope = request.GetDependencyScope();
     return scope.GetService(controllerType) as IHttpController;
 }
开发者ID:devworker55,项目名称:SourceLab,代码行数:8,代码来源:StructureMapUniResolver.cs

示例7: Create

        /// <summary>
        /// Creates the <see cref="IHttpController"/> specified by <paramref name="controllerType"/> using the given <paramref name="request"/>
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <param name="controllerDescriptor">The controller descriptor</param>
        /// <returns>An instance of type <paramref name="controllerType"/>.</returns>
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

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

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

            try
            {
                // First check in the local fast cache and if not a match then look in the broader 
                // HttpControllerDescriptor.Properties cache
                if (_fastCache == null)
                {
                    // If dependency resolver returns controller object then keep asking it whenever we need a new instance
                    IHttpController instance = (IHttpController)request.GetDependencyScope().GetService(controllerType);
                    if (instance != null)
                    {
                        return instance;
                    }

                    // Otherwise create a delegate for creating a new instance of the type
                    Func<IHttpController> activator = TypeActivator.Create<IHttpController>(controllerType);
                    Tuple<HttpControllerDescriptor, Func<IHttpController>> cacheItem = Tuple.Create(controllerDescriptor, activator);
                    Interlocked.CompareExchange(ref _fastCache, cacheItem, null);

                    // Execute the delegate
                    return activator();
                }
                else if (_fastCache.Item1 == controllerDescriptor)
                {
                    // If the key matches and we already have the delegate for creating an instance then just execute it
                    return _fastCache.Item2();
                }
                else
                {
                    // If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for
                    // that HttpControllerDescriptor instance
                    Func<IHttpController> activator = (Func<IHttpController>)controllerDescriptor.Properties.GetOrAdd(
                        _cacheKey,
                        key => TypeActivator.Create<IHttpController>(controllerType));
                    return activator();
                }
            }
            catch (Exception ex)
            {
                throw Error.InvalidOperation(ex, SRResources.DefaultControllerFactory_ErrorCreatingController, controllerType.Name);
            }
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:65,代码来源:DefaultHttpControllerActivator.cs

示例8: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var contextManager = request.GetDependencyScope().GetService(typeof(IContextManager)) as IContextManager;

            if (contextManager != null)
                request.RegisterForDispose(contextManager);

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:ziyasal,项目名称:RepositoryT.EntityFramework,代码行数:9,代码来源:PerRequestContextHandler.cs

示例9: EnsureCache

        protected virtual void EnsureCache(HttpConfiguration config, HttpRequestMessage req)
        {
            object cache;
            config.Properties.TryGetValue(typeof (IApiOutputCache), out cache);

            var cacheFunc = cache as Func<IApiOutputCache>;

            _webApiCache = cacheFunc != null ? cacheFunc() : req.GetDependencyScope().GetService(typeof(IApiOutputCache)) as IApiOutputCache ?? new MemoryCacheDefault();
        }
开发者ID:CodyClark,项目名称:AspNetWebApi-OutputCache,代码行数:9,代码来源:CacheOutputAttribute.cs

示例10: SendAsync

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Message handler is created on application start, not per request, so we need to resolve the authentication service using the dependencyscope (this is in request scope)
            _authenticationService = request.GetDependencyScope().GetService(typeof(IAuthenticationService)) as IAuthenticationService;
            
            if (_authenticationService == null)
            {
                throw new ApplicationException("Authentication service cannot be resolved");
            }

            // Try get authentication header
            var authorisationHeader = request.Headers.Authorization;

            // If authentication header is available and is set to basic authentication
            if (authorisationHeader != null && Scheme.Equals(authorisationHeader.Scheme))
            {
                string username;
                string password;
                
                try
                {
                    username = authorisationHeader.Username();
                    password = authorisationHeader.Password();
                }
                catch
                {
                    // If authorization header cannot be properly read, give back sensible error
                    return request.CreateResponse(HttpStatusCode.BadRequest, "Authorization header is not properly formatted.");
                }

                // Authenticate request
                var authenticateResponse = _authenticationService.IsAuthenticated(username, password);

                // Set user if authentication is successfull
                if (authenticateResponse)
                {
                    var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Password);
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, username));

                    // Do not use thread.principal or httpcontext to set user. This will create dependency on system.web, which stands in the way of self hosting
                    // http://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/
                    request.GetRequestContext().Principal = new ClaimsPrincipal(claimsIdentity);
                }
            }

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

            // Add header to indicate basic authentication is needed when request is unauthorized
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(Scheme));
                response.Content = new JsonContent(new { Error = "Unauthorized" });
            }

            return response;
        }
开发者ID:robinvanderknaap,项目名称:PizzaApi,代码行数:57,代码来源:AuthenticationHandler.cs

示例11: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var existingScope = request.GetDependencyScope();
            var dependencyScope = request.GetSuperscribeDependencyScope(existingScope);

            request.Properties[HttpPropertyKeys.DependencyScope] = dependencyScope;
            request.RegisterForDispose(dependencyScope);

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:c4net,项目名称:Superscribe,代码行数:10,代码来源:SuperscribeDependencyScopeHandler.cs

示例12: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var loggingService = LoggingService ?? request.GetDependencyScope().GetService(typeof (ILoggingService)) as ILoggingService;
            if (loggingService != null)
            {
                loggingService.Log(request.RequestUri.ToString());    
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:10,代码来源:LoggingHandler.cs

示例13: UpdateScopeWithHttpRequestMessage

        /// <summary>
        /// Updates the current dependency scope with current HTTP request message.
        /// </summary>
        /// <param name="request">The HTTP request message.</param>
        internal static void UpdateScopeWithHttpRequestMessage(HttpRequestMessage request)
        {
            var scope = request.GetDependencyScope();
            var requestScope = scope.GetRequestLifetimeScope();
            if (requestScope == null) return;

            var registry = requestScope.ComponentRegistry;
            var builder = new ContainerBuilder();
            builder.Register(c => request).InstancePerApiRequest();
            builder.Update(registry);
        }
开发者ID:yuleyule66,项目名称:autofac,代码行数:15,代码来源:CurrentRequestHandler.cs

示例14: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var scope = request.GetDependencyScope();
            var service = scope.GetService(typeof (IService)) as IService;
            if (service != null)
            {
                Debug.WriteLine(service.SaySomething("Something from a handler"));
            }

            return base.SendAsync(request, cancellationToken);
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:11,代码来源:SampleHandler.cs

示例15: GetUnitOfWork

        private static IUnitOfWork GetUnitOfWork(HttpRequestMessage request)
        {
            var unitOfWork = request.GetDependencyScope().GetService(typeof (IUnitOfWork)) as IUnitOfWork;

            if (unitOfWork == null)
            {
                throw new InvalidOperationException("UOW is missing");
            }

            return unitOfWork;
        }
开发者ID:lucamilan,项目名称:CleanAndTestable,代码行数:11,代码来源:UnitOfWorkActionFilter.cs


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