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


C# IRequest.GetSession方法代码示例

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


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

示例1: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (AuthenticateService.AuthProviders == null)
                throw new InvalidOperationException(
                    "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");

            var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
                this.Provider.IsNullOrEmpty()
                || x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
                    .Fmt(this.Provider ?? "any"));
                res.EndRequest();
                return;
            }

            if (matchingOAuthConfigs.Any(x => x.Provider == DigestAuthProvider.Name))
                AuthenticateIfDigestAuth(req, res);

            if (matchingOAuthConfigs.Any(x => x.Provider == BasicAuthProvider.Name))
                AuthenticateIfBasicAuth(req, res);

            var session = req.GetSession();
            if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
            {
                if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;

                AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
            }
        }
开发者ID:tystol,项目名称:ServiceStack,代码行数:32,代码来源:AuthenticateAttribute.cs

示例2: Log

        public void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration)
        {
            var requestType = requestDto != null ? requestDto.GetType() : null;

            if (ExcludeRequestDtoTypes != null
                && requestType != null
                && ExcludeRequestDtoTypes.Contains(requestType))
                return;
                
            var entry = new RequestLogEntry {
                Id = Interlocked.Increment(ref requestId),
                DateTime = DateTime.UtcNow,
                RequestDuration = requestDuration,
            };

            if (request != null)
            {
                entry.HttpMethod = request.Verb;
                entry.AbsoluteUri = request.AbsoluteUri;
                entry.PathInfo = request.PathInfo;
                entry.IpAddress = request.UserHostAddress;
                entry.ForwardedFor = request.Headers[HttpHeaders.XForwardedFor];
                entry.Referer = request.Headers[HttpHeaders.Referer];
                entry.Headers = request.Headers.ToDictionary();
                entry.UserAuthId = request.GetItemOrCookie(HttpHeaders.XUserAuthId);
                entry.SessionId = request.GetSessionId();
                entry.Items = SerializableItems(request.Items);
                entry.Session = EnableSessionTracking ? request.GetSession() : null;
            }

            if (HideRequestBodyForRequestDtoTypes != null
                && requestType != null
                && !HideRequestBodyForRequestDtoTypes.Contains(requestType)) 
            {
                entry.RequestDto = requestDto;
                if (request != null)
                {
                    entry.FormData = request.FormData.ToDictionary();

                    if (EnableRequestBodyTracking)
                    {
                        entry.RequestBody = request.GetRawBody();
                    }
                }
            }
            if (!response.IsErrorResponse()) {
                if (EnableResponseTracking)
                    entry.ResponseDto = response;
            }
            else {
                if (EnableErrorTracking)
                    entry.ErrorResponse = ToSerializableErrorResponse(response);
            }

            logEntries.Enqueue(entry);

            RequestLogEntry dummy;
            if (logEntries.Count > capacity)
                logEntries.TryDequeue(out dummy);
        }
开发者ID:nustack,项目名称:ServiceStack,代码行数:60,代码来源:InMemoryRollingRequestLogger.cs

示例3: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (AuthenticateService.AuthProviders == null)
                throw new InvalidOperationException(
                    "The AuthService must be initialized by calling AuthService.Init to use an authenticate attribute");

            if (HostContext.HasValidAuthSecret(req))
                return;

            var matchingOAuthConfigs = AuthenticateService.AuthProviders.Where(x =>
                this.Provider.IsNullOrEmpty()
                || x.Provider == this.Provider).ToList();

            if (matchingOAuthConfigs.Count == 0)
            {
                res.WriteError(req, requestDto, $"No OAuth Configs found matching {this.Provider ?? "any"} provider");
                res.EndRequest();
                return;
            }

            req.PopulateFromRequestIfHasSessionId(requestDto);

            //Call before GetSession so Exceptions can bubble
            req.Items[Keywords.HasPreAuthenticated] = true;
            matchingOAuthConfigs.OfType<IAuthWithRequest>()
                .Each(x => x.PreAuthenticate(req, res));

            var session = req.GetSession();
            if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
            {
                if (this.DoHtmlRedirectIfConfigured(req, res, true)) return;

                AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
            }
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:35,代码来源:AuthenticateAttribute.cs

示例4: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (HostContext.HasValidAuthSecret(req))
                return;

            base.Execute(req, res, requestDto); //first check if session is authenticated
            if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            var session = req.GetSession();

            var authRepo = HostContext.AppHost.GetAuthRepository(req);
            using (authRepo as IDisposable)
            {
                if (session != null && session.HasRole(RoleNames.Admin, authRepo))
                    return;

                if (HasAnyPermissions(req, session, authRepo)) return;
            }

            if (DoHtmlRedirectIfConfigured(req, res)) return;

            res.StatusCode = (int)HttpStatusCode.Forbidden;
            res.StatusDescription = ErrorMessages.InvalidPermission;
            res.EndRequest();
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:25,代码来源:RequiresAnyPermission.cs

示例5: RequestFilter

        public void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            // Get the active user's session
            var session = req.GetSession() as MyServiceUserSession;
            if(session == null || session.UserAuthId == 0)
                throw HttpError.Unauthorized("You do not have a valid session");

            // Determine the Id of the requested object, if applicable
            int? objectId = null;
            var property = requestDto.GetType().GetPublicProperties().FirstOrDefault(p=>Attribute.IsDefined(p, typeof(ObjectIdAttribute)));
            if(property != null)
                objectId = property.GetValue(requestDto,null) as int?;

            // You will want to use your database here instead to the Mock database I'm using
            // So resolve it from the container
            // var db = HostContext.TryResolve<IDbConnectionFactory>().OpenDbConnection());
            // You will need to write the equivalent 'hasPermission' query with your provider

            // Get the most appropriate permission
            // The orderby clause ensures that priority is given to object specific permissions first, belonging to the user, then to groups having the permission
            // descending selects int value over null
            var hasPermission = session.IsAdministrator ||
                                (from p in Db.Permissions
                                 where p.ObjectType == objectType && ((p.ObjectId == objectId || p.ObjectId == null) && (p.UserId == session.UserAuthId || p.UserId == null) && (session.Groups.Contains(p.GroupId) || p.GroupId == null))
                                 orderby p.ObjectId descending, p.UserId descending, p.Permitted, p.GroupId descending
                                 select p.Permitted).FirstOrDefault();

            if(!hasPermission)
                throw new HttpError(System.Net.HttpStatusCode.Forbidden, "Forbidden", "You do not have permission to access the requested object");
        }
开发者ID:scottmcarthur,项目名称:ServiceStackAdvancedPermissions,代码行数:30,代码来源:Permission.cs

示例6: AssertRequiredRoles

        /// <summary>
        /// Check all session is in all supplied roles otherwise a 401 HttpError is thrown
        /// </summary>
        /// <param name="req"></param>
        /// <param name="requiredRoles"></param>
        public static void AssertRequiredRoles(IRequest req, params string[] requiredRoles)
        {
            if (requiredRoles.IsEmpty()) return;

            if (HostContext.HasValidAuthSecret(req))
                return;

            var session = req.GetSession();

            if (session != null)
            {
                if (session.HasRole(RoleNames.Admin))
                    return;
                if (requiredRoles.All(session.HasRole))
                    return;
            }

            session.UpdateFromUserAuthRepo(req);

            if (session != null && requiredRoles.All(session.HasRole))
                return;

            var statusCode = session != null && session.IsAuthenticated
                ? (int)HttpStatusCode.Forbidden
                : (int)HttpStatusCode.Unauthorized;

            throw new HttpError(statusCode, "Invalid Role");
        }
开发者ID:GDBSD,项目名称:ServiceStack,代码行数:33,代码来源:RequiredRoleAttribute.cs

示例7: AssertRequiredRoles

        /// <summary>
        /// Check all session is in any supplied roles otherwise a 401 HttpError is thrown
        /// </summary>
        /// <param name="request"></param>
        /// <param name="requiredRoles"></param>
        public static void AssertRequiredRoles(IRequest req, params string[] requiredRoles)
        {
            if (requiredRoles.IsEmpty()) return;

            if (HostContext.HasValidAuthSecret(req))
                return;

            var session = req.GetSession();

            var authRepo = HostContext.AppHost.GetAuthRepository(req);
            using (authRepo as IDisposable)
            {
                if (session != null && session.HasRole(RoleNames.Admin, authRepo))
                    return;

                if (session != null && session.UserAuthId != null && requiredRoles.Any(x => session.HasRole(x, authRepo)))
                    return;

                session.UpdateFromUserAuthRepo(req);

                if (session != null && session.UserAuthId != null && requiredRoles.Any(x => session.HasRole(x, authRepo)))
                    return;
            }

            var statusCode = session != null && session.IsAuthenticated
                ? (int)HttpStatusCode.Forbidden
                : (int)HttpStatusCode.Unauthorized;

            throw new HttpError(statusCode, "Invalid Role");
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:35,代码来源:RequiresAnyRoleAttribute.cs

示例8: CreateEntry

        protected RequestLogEntry CreateEntry(IRequest request, object requestDto, object response, TimeSpan requestDuration, Type requestType)
        {
            var entry = new RequestLogEntry
            {
                Id = Interlocked.Increment(ref requestId),
                DateTime = DateTime.UtcNow,
                RequestDuration = requestDuration,
            };

            if (request != null)
            {
                entry.HttpMethod = request.Verb;
                entry.AbsoluteUri = request.AbsoluteUri;
                entry.PathInfo = request.PathInfo;
                entry.IpAddress = request.UserHostAddress;
                entry.ForwardedFor = request.Headers[HttpHeaders.XForwardedFor];
                entry.Referer = request.Headers[HttpHeaders.Referer];
                entry.Headers = request.Headers.ToDictionary();
                entry.UserAuthId = request.GetItemOrCookie(HttpHeaders.XUserAuthId);
                entry.SessionId = request.GetSessionId();
                entry.Items = SerializableItems(request.Items);
                entry.Session = EnableSessionTracking ? request.GetSession() : null;
                new NameValueCollection().ToDictionary();
            }

            if (HideRequestBodyForRequestDtoTypes != null
                && requestType != null
                && !HideRequestBodyForRequestDtoTypes.Contains(requestType))
            {
                entry.RequestDto = requestDto;
                if (request != null)
                {
                    entry.FormData = request.FormData.ToDictionary();

                    if (EnableRequestBodyTracking)
                    {
                        entry.RequestBody = request.GetRawBody();
                    }
                }
            }
            if (!response.IsErrorResponse())
            {
                if (EnableResponseTracking)
                    entry.ResponseDto = response;
            }
            else
            {
                if (EnableErrorTracking)
                    entry.ErrorResponse = ToSerializableErrorResponse(response);
            }

            return entry;
        }
开发者ID:softwx,项目名称:ServiceStack,代码行数:53,代码来源:InMemoryRollingRequestLogger.cs

示例9: GetUsernameFromRequest

        public static string GetUsernameFromRequest(IRequest request)
        {
            if (string.IsNullOrEmpty(request.GetBasicAuth()))
            {
                return request.GetSession().UserAuthName ?? "API";
            }

            var bytes = Convert.FromBase64String(request.GetBasicAuth());
            var usernamePassword = Encoding.UTF8.GetString(bytes);

            var username = usernamePassword.Split(':').First();
            return username;
        }
开发者ID:CodeRevver,项目名称:notekeeper-api,代码行数:13,代码来源:ApiHostNameProvider.cs

示例10: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            base.Execute(req, res, requestDto); //first check if session is authenticated
            if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            var session = req.GetSession();
            if (HasAnyPermissions(req, session)) return;

            if (DoHtmlRedirectIfConfigured(req, res)) return;

            res.StatusCode = (int)HttpStatusCode.Forbidden;
            res.StatusDescription = "Invalid Permission";
            res.EndRequest();
        }
开发者ID:vebin,项目名称:soa,代码行数:14,代码来源:RequiresAnyPermission.cs

示例11: OnRequestEnd

        private void OnRequestEnd(IRequest request, IResponse response, object dto)
        {
            if (!request.Items.ContainsKey(SessionCopyRequestItemKey)) return;
            var copy = request.Items[SessionCopyRequestItemKey] as IWebSudoAuthSession;
            if (copy == null) return;

            var session = request.GetSession();
            if (!session.IsAuthenticated)
            {
                // if the credential check failed, restore the session to it's prior, valid state.
                // this enures that a logged in user, remains logged in, but not elevated if the check failed.
                session.PopulateWith(copy);
            }

            request.SaveSession(session);
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:16,代码来源:WebSudoFeature.cs

示例12: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (HostContext.AppHost.HasValidAuthSecret(req))
                return;

            base.Execute(req, res, requestDto);
            if (res.IsClosed)
                return;

            var session = req.GetSession();
            if (session != null && session.HasRole("Admin")
                || (this.HasWebSudo(req, session as IWebSudoAuthSession)
                || this.DoHtmlRedirectIfConfigured(req, res)))
                return;

            res.StatusCode = 402;
            res.StatusDescription = "Web Sudo Required";
            res.EndRequest();
        }
开发者ID:jin29neci,项目名称:ServiceStack,代码行数:19,代码来源:WebSudoRequiredAttribute.cs

示例13: GetConsumerId

        public virtual string GetConsumerId(IRequest request)
        {
            if (AuthenticateService.AuthProviders == null)
            {
                throw new InvalidOperationException(
                    "AuthService not initialized. This is required for generating default ConsumerId for RateLimitting.");
            }

            IAuthSession userSession = request.GetSession();

            // TODO This will need more love to authorize user rather than just verify authentication (not necessarily here but in general)
            if (!IsUserAuthenticated(userSession))
            {
                log.Error($"User {userSession?.UserName ?? "<unknown>"} not authenticated for request {request.AbsoluteUri}");
                throw new AuthenticationException("You must be authenticated to access this service");
            }

            return userSession.UserAuthId?.ToLowerInvariant();
        }
开发者ID:yonglehou,项目名称:servicestack-ratelimit-redis,代码行数:19,代码来源:LimitKeyGenerator.cs

示例14: OnRequestStart

        private void OnRequestStart(IRequest request, IResponse response, object dto)
        {
            if (dto == null) return;

            var session = request.GetSession();
            if (!session.IsAuthenticated) return;

            var authenticateDto = dto as Authenticate;
            if (authenticateDto != null && !AuthenticateService.LogoutAction.EqualsIgnoreCase(authenticateDto.provider))
            {
                var copy = AuthenticateService.CurrentSessionFactory().PopulateWith(session);

                request.Items[SessionCopyRequestItemKey] = copy;

                // clear details to allow credentials to be rechecked, 
                // otherwise IsAuthorized will just return, bypassing the auth provider's Authenticate method
                // fields cleared LoginMatchesSession
                session.UserAuthName = null;
                session.Email = null;
            }
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:21,代码来源:WebSudoFeature.cs

示例15: Execute

        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (HostContext.AppHost.HasValidAuthSecret(req))
                return;

            base.Execute(req, res, requestDto); //first check if session is authenticated
            if (res.IsClosed) return; //AuthenticateAttribute already closed the request (ie auth failed)

            var session = req.GetSession();

            if (session != null && session.HasRole(RoleNames.Admin))
                return;

            if (HasAllRoles(req, session)) return;

            if (DoHtmlRedirectIfConfigured(req, res)) return;

            res.StatusCode = (int)HttpStatusCode.Forbidden;
            res.StatusDescription = "Invalid Role";
            res.EndRequest();
        }
开发者ID:GDBSD,项目名称:ServiceStack,代码行数:21,代码来源:RequiredRoleAttribute.cs


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