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


C# IRequestContext.Get方法代码示例

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


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

示例1: SerializeToStream

        public void SerializeToStream(IRequestContext requestContext, object dto, IHttpResponse httpRes)
        {
            var httpReq = requestContext.Get<IHttpRequest>();
            if (AppHost.ViewEngines.Any(x => x.ProcessRequest(httpReq, httpRes, dto))) return;

            if (requestContext.ResponseContentType != ContentType.Html
                && httpReq.ResponseContentType != ContentType.JsonReport) return;

            // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
            var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
            json = json.Replace("<", "&lt;").Replace(">", "&gt;");

            var url = httpReq.AbsoluteUri
                .Replace("format=html", "")
                .Replace("format=shtm", "")
                .TrimEnd('?', '&');

            url += url.Contains("?") ? "&" : "?";

            var now = DateTime.UtcNow;
            var requestName = httpReq.OperationName ?? dto.GetType().Name;

            string html = GetHtmlTemplate()
                .Replace("${Dto}", json)
                .Replace("${Title}", string.Format(TitleFormat, requestName, now))
                .Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes().ToString())
                .Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
                .Replace("${ServiceUrl}", url);

            var utf8Bytes = html.ToUtf8Bytes();
            httpRes.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
        }
开发者ID:rajeshpillai,项目名称:ServiceStack,代码行数:32,代码来源:HtmlFormat.cs

示例2: Log

        public void Log(IRequestContext requestContext, object requestDto)
        {
            var httpReq = requestContext.Get<IHttpRequest>();
            var entry = new RequestLogEntry {
                Id = Interlocked.Increment(ref requestId),
                DateTime = DateTime.UtcNow,
                HttpMethod = httpReq.HttpMethod,
                AbsoluteUri = httpReq.AbsoluteUri,
                IpAddress = requestContext.IpAddress,
                PathInfo = httpReq.PathInfo,
                Referer = httpReq.Headers[HttpHeaders.Referer],
                Headers = httpReq.Headers.ToDictionary(),
                UserAuthId = httpReq.GetItemOrCookie(HttpHeaders.XUserAuthId),
                SessionId = httpReq.GetSessionId(),
                Items = httpReq.Items,
            };

            if (HideRequestBodyForRequestDtoTypes != null
                && requestDto != null
                && !HideRequestBodyForRequestDtoTypes.Contains(requestDto.GetType()))
            {
                entry.RequestDto = requestDto;
                entry.FormData = httpReq.FormData.ToDictionary();
            }

            logEntries.Enqueue(entry);

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

示例3: Post

		public static Response<Asiento> Post(this Asiento request,
		                                     Factory factory,
		                                     IRequestContext requestContext,
		                                     bool checkSucursal=true,
		                                     bool checkPeriodo=true,
		                                     Action<IDbCommand,Asiento> runBeforePostDbCommandsFn=null,
		                                     Action<IDbCommand,Asiento> runAfterPostDbCommandsFn=null)
		{
			
						
			var httpRequest = requestContext.Get<IHttpRequest>();		
			request.ValidateAndThrowHttpError(Operaciones.Create,httpRequest, factory);
						
			if(checkSucursal) request.CheckSucursal(factory, httpRequest);
						
			request.Periodo= request.Fecha.ObtenerPeriodo();
			
			if(checkPeriodo) request.CheckPeriodo(factory,httpRequest);			
									
						
			try
			{
				SqlExpressionVisitor<Asiento> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Asiento>();
				ev.Insert( f=> new { f.Id, f.Descripcion, f.Fecha , f.Periodo, f.IdSucursal,f.Numero,f.CodigoDocumento,f.Documento });                  
				
				var data = factory.Post<Asiento>(request,ev,
				dbCmd=>
				{
					request.Numero= dbCmd.GetConsecutivo(request.IdSucursal,Definiciones.ComprobranteContable,
					                                     httpRequest).Numero;
					
					if(request.Documento.IsNullOrEmpty()) request.Documento=request.Numero.ToString();
					
					if(runBeforePostDbCommandsFn!=null) runBeforePostDbCommandsFn(dbCmd,request);					
				},
				(dbCmd,result)=>
				{
					httpRequest.CacheClientExec(
					cache=>
						cache.Set(result.GetCacheKey(),
					          result,
					          TimeSpan.FromDays(Definiciones.DiasEnCache))
					);
					if(runAfterPostDbCommandsFn!=null) runAfterPostDbCommandsFn(dbCmd,result);
				});
				
				return new Response<Asiento>(){
				Data= data
				};
			}
			catch(Exception e ){
				throw new HttpError(e.Message);
			}
			
		}
开发者ID:aicl,项目名称:Aicl.Galapago,代码行数:55,代码来源:AsientoExtensiones.cs

示例4: AssertRequiredRoles

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

            var req = requestContext.Get<IHttpRequest>();
            var session = req.GetSession();

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

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

示例5: FieldsFromQueryString

        public static string FieldsFromQueryString(IRequestContext requestContext, string fieldsQueryStringName)
        {
            var httpRequest = requestContext.Get<IHttpRequest>();

            if (httpRequest == null)
            {
                return string.Empty;
            }
            if (httpRequest.QueryString == null)
            {
                return string.Empty;
            }

            return httpRequest.QueryString.Get(fieldsQueryStringName);
        }
开发者ID:AnthonyCarl,项目名称:ServiceStack.PartialResponse,代码行数:15,代码来源:FieldsRetriever.cs

示例6: GetAuthorizations

		public static AuthorizationResponse GetAuthorizations(this Authorization request, 
		                                           Factory factory, IRequestContext requestContext){
			
			var httpRequest = requestContext.Get<IHttpRequest>();	
			IAuthSession session = httpRequest.GetSession();
						
			if (!session.HasRole(RoleNames.Admin))
			{
				request.UserId= int.Parse(session.UserAuthId);
			}
			
			List<AuthRole> roles = new List<AuthRole>();
			List<AuthPermission> permissions= new List<AuthPermission>();
			
            List<AuthRoleUser> aur= new List<AuthRoleUser>();
            List<AuthRole> rol = new List<AuthRole>();
            List<AuthPermission> per = new List<AuthPermission>();
            List<AuthRolePermission> rol_per = new List<AuthRolePermission>();
            
            factory.Execute(proxy=>
            {
				aur=  proxy.Get<AuthRoleUser>(q=>q.UserId==request.UserId);
				//proxy.GetByUserIdFromCache<AuthRoleUser>(request.UserId); // causa problemas .net !!! no en mono
                rol= proxy.GetFromCache<AuthRole>();
                per= proxy.GetFromCache<AuthPermission>();
                rol_per= proxy.GetFromCache<AuthRolePermission>();
            
                foreach( var r in aur)
                {
                    AuthRole ar= rol.First(x=>x.Id== r.AuthRoleId);
                    roles.Add(ar);
                    rol_per.Where(q=>q.AuthRoleId==ar.Id).ToList().ForEach(y=>{
                        AuthPermission up=  per.First( p=> p.Id== y.AuthPermissionId);
                        if( permissions.FindIndex(f=>f.Name==up.Name)<0) // .IndexOf(up) <0)
                            permissions.Add(up);
                    }) ;
                };    

            });
			
			return new AuthorizationResponse(){
				Permissions= permissions,
				Roles= roles,
			};
		}			
开发者ID:angelcolmenares,项目名称:Aicl.Delfin,代码行数:45,代码来源:BL.Authorization.cs

示例7: Get

        public static AuthorizationResponse Get(this Authorization request, 
                                                   Factory factory, IRequestContext requestContext){
            
            var httpRequest = requestContext.Get<IHttpRequest>();   
            IAuthSession session = httpRequest.GetSession();
                        
            if (!session.HasRole(RoleNames.Admin))
            {
                request.UserId= int.Parse(session.UserAuthId);
            }
            
            List<AuthRole> roles = new List<AuthRole>();
            List<string> permissions= new List<string>();
            
            List<AuthRoleUser> aur= new List<AuthRoleUser>();
            List<AuthRole> rol = new List<AuthRole>();
            List<AuthPermission> per = new List<AuthPermission>();
            List<AuthRolePermission> rol_per = new List<AuthRolePermission>();
           
            factory.Execute(proxy=>
            {
                aur= proxy.Get<AuthRoleUser>(r=>r.IdUsuario==request.UserId );
                rol= proxy.Get<AuthRole>(); //DAL.GetFromCache<AuthRole>(proxy);
                per= proxy.Get<AuthPermission>(); //DAL.GetFromCache<AuthPermission >(proxy);
                rol_per= proxy.Get<AuthRolePermission>(); //DAL.GetFromCache<AuthRolePermission >(proxy);

            });
                        
            foreach( var r in aur)
            {
                AuthRole ar= rol.First(x=>x.Id== r.IdAuthRole);
                roles.Add(ar);
                rol_per.Where(q=>q.IdAuthRole==ar.Id).ToList().ForEach(y=>{
                    AuthPermission up=  per.First( p=> p.Id== y.IdAuthPermission);
                    if( permissions.IndexOf(up.Name) <0)
                        permissions.Add(up.Name);
                }) ;
            };
                               
            return new AuthorizationResponse(){
                Permissions= permissions,
                Roles= roles

            };
        }
开发者ID:angelcolmenares,项目名称:Aicl.Colmetrik,代码行数:45,代码来源:AuthorizationExtensions.cs

示例8: AssertRequiredRoles

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

            var req = requestContext.Get<IHttpRequest>();
            var session = req.GetSession();

            if (session != null && 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:grammarware,项目名称:fodder,代码行数:26,代码来源:src_ServiceStack_ServiceInterface_RequiredRoleAttribute.cs

示例9: SerializeToStream

        public static void SerializeToStream(IRequestContext requestContext, object dto, Stream stream)
        {
            var httpReq = requestContext.Get<IHttpRequest>();
            if (requestContext.ResponseContentType != ContentType.Html
                && httpReq.ResponseContentType != ContentType.ServerHtml) return;

            var json = JsonSerializer.SerializeToString(dto);

            var url = httpReq.AbsoluteUri
                .Replace("format=html", "")
                .Replace("format=shtm", "")
                .TrimEnd('?', '&');

            var now = DateTime.UtcNow;

            var requestName = httpReq.OperationName ?? dto.GetType().Name;

            var html = string.Format(Template,
              json,
              string.Format(TitleFormat, requestName, now),
              string.Format(HtmlTitleFormat, requestName, now),
              url);

            var utf8Bytes = html.ToUtf8Bytes();
            stream.Write(utf8Bytes, 0, utf8Bytes.Length);
        }
开发者ID:macca16,项目名称:ServiceStack,代码行数:26,代码来源:HtmlFormat.cs

示例10: WriteToResponse

        /// <summary>
        /// Writes to response.
        /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param>
        /// <param name="defaultAction">The default action.</param>
        /// <param name="serializerCtx">The serialization context.</param>
        /// <param name="bodyPrefix">Add prefix to response body if any</param>
        /// <param name="bodySuffix">Add suffix to response body if any</param>
        /// <returns></returns>
        public static bool WriteToResponse(this IHttpResponse response, object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, byte[] bodyPrefix, byte[] bodySuffix)
        {
            using (Profiler.Current.Step("Writing to Response"))
            {
                var defaultContentType = serializerCtx.ResponseContentType;
                try
                {
                    if (result == null)
                    {
                        response.EndHttpRequestWithNoContent();
                        return true;
                    }

                    ApplyGlobalResponseHeaders(response);

                    var httpResult = result as IHttpResult;
                    if (httpResult != null)
                    {
                        if (httpResult.RequestContext == null)
                        {
                            httpResult.RequestContext = serializerCtx;
                        }

                        var httpError = httpResult as IHttpError;
                        if (httpError != null)
                        {
                            if (response.HandleCustomErrorHandler(serializerCtx.Get<IHttpRequest>(),
                                defaultContentType, httpError.Status, httpError.ToErrorResponse()))
                            {
                                return true;
                            }
                        }

                        response.StatusCode = httpResult.Status;
                        response.StatusDescription = httpResult.StatusDescription ?? httpResult.StatusCode.ToString();
                        if (string.IsNullOrEmpty(httpResult.ContentType))
                        {
                            httpResult.ContentType = defaultContentType;
                        }
                        response.ContentType = httpResult.ContentType;
                    }

                    /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */
                    var responseOptions = result as IHasOptions;
                    if (responseOptions != null)
                    {
                        //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction)
                        const string reservedOptions = ".";

                        foreach (var responseHeaders in responseOptions.Options)
                        {
                            if (responseHeaders.Key.Contains(reservedOptions)) continue;

                            Log.DebugFormat("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value);
                            response.AddHeader(responseHeaders.Key, responseHeaders.Value);
                        }
                    }

                    var disposableResult = result as IDisposable;
                    if (WriteToOutputStream(response, result, bodyPrefix, bodySuffix))
                    {
                        response.Flush(); //required for Compression
                        if (disposableResult != null) disposableResult.Dispose();
                        return true;
                    }

                    if (httpResult != null)
                    {
                        result = httpResult.Response;
                    }

                    //ContentType='text/html' is the default for a HttpResponse
                    //Do not override if another has been set
                    if (response.ContentType == null || response.ContentType == ContentType.Html)
                    {
                        response.ContentType = defaultContentType;
                    }
                    if (bodyPrefix != null && response.ContentType.IndexOf(ContentType.Json, StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        response.ContentType = ContentType.JavaScript;
                    }

                    if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType))
                    {
                        response.ContentType += ContentType.Utf8Suffix;
                    }

                    var responseText = result as string;
                    if (responseText != null)
//.........这里部分代码省略.........
开发者ID:h2oman,项目名称:ServiceStack,代码行数:101,代码来源:IHttpResponseExtensions.cs

示例11: Log

        public void Log(IRequestContext requestContext, 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,
            };

            var httpReq = requestContext != null ? requestContext.Get<IHttpRequest>() : null;
            if (httpReq != null)
            {
                entry.HttpMethod = httpReq.HttpMethod;
                entry.AbsoluteUri = httpReq.AbsoluteUri;
                entry.PathInfo = httpReq.PathInfo;
                entry.IpAddress = requestContext.IpAddress;
                entry.ForwardedFor = httpReq.Headers[HttpHeaders.XForwardedFor];
                entry.Referer = httpReq.Headers[HttpHeaders.Referer];
                entry.Headers = httpReq.Headers.ToDictionary();
                entry.UserAuthId = httpReq.GetItemOrCookie(HttpHeaders.XUserAuthId);
                entry.SessionId = httpReq.GetSessionId();
                entry.Items = httpReq.Items;
                entry.Session = EnableSessionTracking ? httpReq.GetSession() : null;
            }

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

                    if (EnableRequestBodyTracking)
                    {
                        entry.RequestBody = httpReq.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:ELHANAFI,项目名称:ServiceStack,代码行数:61,代码来源:InMemoryRollingRequestLogger.cs

示例12: SerializeToStream

        /// <summary>
        /// Render Markdown for text/markdown and text/plain ContentTypes
        /// </summary>
        public void SerializeToStream(IRequestContext requestContext, object dto, Stream stream)
        {
            MarkdownPage markdownPage;
            if ((markdownPage = GetViewPageByResponse(dto, requestContext.Get<IHttpRequest>())) == null)
                throw new InvalidDataException(ErrorPageNotFound.FormatWith(GetPageName(dto, requestContext)));

            ReloadModifiedPageAndTemplates(markdownPage);

            const bool renderHtml = false; //i.e. render Markdown
            var markup = RenderStaticPage(markdownPage, renderHtml);
            var markupBytes = markup.ToUtf8Bytes();
            stream.Write(markupBytes, 0, markupBytes.Length);
        }
开发者ID:Arxisos,项目名称:ServiceStack,代码行数:16,代码来源:MarkdownFormat.cs

示例13: GetPageName

 public string GetPageName(object dto, IRequestContext requestContext)
 {
     var httpRequest = requestContext != null ? requestContext.Get<IHttpRequest>() : null;
     var httpResult = dto as IHttpResult;
     if (httpResult != null)
     {
         dto = httpResult.Response;
     }
     if (dto != null) return dto.GetType().Name;
     return httpRequest != null ? httpRequest.OperationName : null;
 }
开发者ID:Arxisos,项目名称:ServiceStack,代码行数:11,代码来源:MarkdownFormat.cs

示例14: Delete

		public static Response<Asiento> Delete(this Asiento request,
		                                     Factory factory,
		                                     IRequestContext requestContext,
		                                     bool checkSucursal=true,
		                                     bool checkPeriodo=false,
		                                     Action<IDbCommand,Asiento> runBeforeDeleteDbCommandsFn=null,
		                                     Action<IDbCommand,Asiento> runAfterDeleteDbCommandsFn=null)
		{
			
			request.CheckId(Operaciones.Destroy);
			
			var httpRequest = requestContext.Get<IHttpRequest>();		
			string lockKey=request.GetLockKey(); 	
						
			Action block=()=>{
		
				factory.Delete(request,(dbCmd)=>
				{	
					httpRequest.CacheClientExec(cache=>
					{
						var id = request.Id;
						var cacheKey=request.GetCacheKey();
						request= cache.Get<Asiento>(cacheKey);
						if(request== default(Asiento))
						{
							request= dbCmd.FirstOrDefault<Asiento>(q=> q.Id==id);
							AssertExists(request, id);	
						}
						else
						{
							cache.Remove(cacheKey);
						}
						
						request.ValidateAndThrowHttpError(Operaciones.Destroy);
												
						if(checkSucursal) request.CheckSucursal(factory, httpRequest);
						if(checkPeriodo)  request.CheckPeriodo(factory,httpRequest);			
						if(runBeforeDeleteDbCommandsFn!=null) runBeforeDeleteDbCommandsFn(dbCmd, request);	
					});
	
				},(dbCmd)=>
				{	
					if(runAfterDeleteDbCommandsFn!=null) runAfterDeleteDbCommandsFn(dbCmd,request);
				});
			}; 			
			
			IRedisClientsManager cm = httpRequest.GetCacheClient() as IRedisClientsManager;
	
			try
			{
				if( cm != null)
				{
					cm.Exec(redisClient=>
					{
						using (redisClient.AcquireLock(lockKey, TimeSpan.FromSeconds(Definiciones.LockSeconds)))
						{
							block();
						}	
					});
				}
				else
					block();
				
				return new Response<Asiento>(){};
			}		
			catch(Exception e)
			{
				throw new HttpError(e.Message);
			}
			
		}
开发者ID:aicl,项目名称:Aicl.Galapago,代码行数:71,代码来源:AsientoExtensiones.cs

示例15: Paginador

 public Pager Paginador(IRequestContext requestContext)
 {
     var httpRequest= requestContext.Get<IHttpRequest>();
     return httpRequest.BuildPager();
 }
开发者ID:angelcolmenares,项目名称:Coral,代码行数:5,代码来源:AppServiceBase.cs


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