예제 #1
0
        public async Task<IResponse> Send(IRequest request, System.Threading.CancellationToken cancellationToken)
        {
            if (request.Method != HttpMethod.Get)
                return await _httpClient.Send(request, cancellationToken);

            var key = "octokit_cache_" + new Uri(request.BaseAddress, request.Endpoint).AbsoluteUri;
            var cachedResponse = await BlobCache.LocalMachine.GetObject<InternalResponse>(key).Catch(Observable.Empty<InternalResponse>()).DefaultIfEmpty();

            if (cachedResponse == null)
            {
                var httpResponse = await _httpClient.Send(request, cancellationToken);
                cachedResponse = new InternalResponse(httpResponse);
                await BlobCache.LocalMachine.InsertObject(key, cachedResponse, TimeSpan.FromMinutes(30));
                return httpResponse;
            }

            if (!String.IsNullOrEmpty(cachedResponse.ApiInfo.Etag))
            {
                request.Headers["If-None-Match"] = String.Format("{0}", cachedResponse.ApiInfo.Etag);
                var conditionalResponse = await _httpClient.Send(request, cancellationToken);
                if (conditionalResponse.StatusCode == HttpStatusCode.NotModified)
                    return new Response(cachedResponse);

                var newResponse = new InternalResponse(conditionalResponse);
                await BlobCache.LocalMachine.InsertObject(key, newResponse, TimeSpan.FromMinutes(30));
                return conditionalResponse;
            }

            var resp = await _httpClient.Send(request, cancellationToken);
            cachedResponse = new InternalResponse(resp);
            await BlobCache.LocalMachine.InsertObject(key, cachedResponse, TimeSpan.FromMinutes(30));
            return resp;
        }
예제 #2
0
 protected override Task OnReceived(IRequest request, string connectionId, string data)
 {
     var key = _senders.ContainsKey(data)
             ? data
             : "*";
     return _senders[key](Connection, request, connectionId, data);
 }
예제 #3
0
        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);
            }
        }
예제 #4
0
        public static void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            if (validator == null) return;

            var validatorWithHttpRequest = validator as IRequiresRequest;
            if (validatorWithHttpRequest != null)
                validatorWithHttpRequest.Request = req;

            var ruleSet = req.Verb;
            var validationResult = validator.Validate(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

            if (validationResult.IsValid) return;

            var errorResponse = DtoUtils.CreateErrorResponse(
                requestDto, validationResult.ToErrorResult());

            var validationFeature = HostContext.GetPlugin<ValidationFeature>();
            if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
            {
                errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
            }

            res.WriteToResponse(req, errorResponse);
        }
 public RequestEntityReaderHydrator(IDependencyResolver resolver, IRequest request)
 {
     this.Log = NullLogger<CodecLogSource>.Instance;
     this.ErrorCollector = NullErrorCollector.Instance;
     this.resolver = resolver;
     this.request = request;
 }
예제 #6
0
 public WebTileProvider(IRequest request = null, IPersistentCache<byte[]> persistentCache = null,
     Func<Uri, byte[]> fetchTile = null)
 {
     Request = request ?? new NullRequest();
     _persistentCache = persistentCache ?? new NullCache();
     _fetchTile = fetchTile ?? (RequestHelper.FetchImage);
 }
예제 #7
0
        public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes);
            if (httpRes.IsClosed) return;

            httpRes.ContentType = MimeTypes.Html;
            if (RazorFormat == null)
                RazorFormat = RazorFormat.Instance;

            var contentPage = RazorPage ?? RazorFormat.FindByPathInfo(PathInfo);
            if (contentPage == null)
            {
                httpRes.StatusCode = (int)HttpStatusCode.NotFound;
                httpRes.EndHttpHandlerRequest();
                return;
            }

            var model = Model;
            if (model == null)
                httpReq.Items.TryGetValue("Model", out model);
            if (model == null)
            {
                var modelType = RazorPage != null ? RazorPage.ModelType : null;
                model = modelType == null || modelType == typeof(DynamicRequestObject)
                    ? null
                    : DeserializeHttpRequest(modelType, httpReq, httpReq.ContentType);
            }

            RazorFormat.ProcessRazorPage(httpReq, contentPage, model, httpRes);
        }
예제 #8
0
 public ListenerResponse(HttpListenerResponse response, IRequest request = null)
 {
     this.response = response;
     this.Request = request;
     this.Cookies = new Cookies(this);
     this.Items = new Dictionary<string, object>();
 }
예제 #9
0
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            try
            {
                var appHost = HostContext.AppHost;
                if (appHost.ApplyPreRequestFilters(httpReq, httpRes)) 
                    return EmptyTask;
                
                var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
                if (restPath == null)
                {
                    return new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo)
                        .AsTaskException();
                }
                httpReq.SetRoute(restPath as RestPath);

                operationName = restPath.RequestType.GetOperationName();

                var callback = httpReq.GetJsonpCallback();
                var doJsonp = HostContext.Config.AllowJsonpRequests
                              && !string.IsNullOrEmpty(callback);

                if (ResponseContentType != null)
                    httpReq.ResponseContentType = ResponseContentType;

                var responseContentType = httpReq.ResponseContentType;
                appHost.AssertContentType(responseContentType);

                var request = httpReq.Dto = CreateRequest(httpReq, restPath);

                if (appHost.ApplyRequestFilters(httpReq, httpRes, request)) 
                    return EmptyTask;

                var rawResponse = GetResponse(httpReq, request);
                return HandleResponse(rawResponse, response => 
                {
                    response = appHost.ApplyResponseConverters(httpReq, response);

                    if (appHost.ApplyResponseFilters(httpReq, httpRes, response)) 
                        return EmptyTask;

                    if (responseContentType.Contains("jsv") && !string.IsNullOrEmpty(httpReq.QueryString[Keywords.Debug]))
                        return WriteDebugResponse(httpRes, response);

                    if (doJsonp && !(response is CompressedResult))
                        return httpRes.WriteToResponse(httpReq, response, (callback + "(").ToUtf8Bytes(), ")".ToUtf8Bytes());
                    
                    return httpRes.WriteToResponse(httpReq, response);
                },  
                ex => !HostContext.Config.WriteErrorsToResponse 
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq)));
            }
            catch (Exception ex)
            {
                return !HostContext.Config.WriteErrorsToResponse
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq));
            }
        }
예제 #10
0
        /// <summary>
        /// Logs the error.
        /// </summary>
        /// <param name="request">Request that failed</param>
        /// <param name="err">Exception which was thrown</param>
        protected virtual void LogError(IRequest request, Exception err)
        {
            var sb = new StringBuilder();
            sb.Append("Failed to handle request ");
            sb.AppendLine(request.Uri.ToString());
            if (request.QueryString.Count > 0)
            {
                sb.AppendLine();
                sb.AppendLine("Query string: ");
                foreach (var var in request.QueryString)
                {
                    sb.AppendLine(string.Format("{0}: {1}", var.Name, string.Join(",", var)));
                }
            }
            if (request.Form.Count > 0)
            {
                sb.AppendLine();
                sb.AppendLine("Form: ");
                foreach (var var in request.QueryString)
                {
                    sb.AppendLine(string.Format("{0}: {1}", var.Name, string.Join(",", var)));
                }
            }
            sb.AppendLine();
            sb.AppendLine("Headers: ");
            foreach (var var in request.Headers)
            {
                sb.AppendLine(string.Format("{0}: {1}", var.Name, var.Value));
            }


            _logger.Error(sb.ToString(), err);
        }
예제 #11
0
        protected override Task OnConnected(IRequest request, string connectionId)
        {
            // Should throw 404
            using (HttpWebRequest.Create("http://httpstat.us/404").GetResponse()) { }

            return base.OnConnected(request, connectionId);
        }
        public IResponse Execute(IRequest cruiseRequest)
        {
            Hashtable velocityContext = new Hashtable();
            IResponse decoratedActionResponse = decoratedAction.Execute(cruiseRequest);
            if (decoratedActionResponse is HtmlFragmentResponse)
            {
                ICruiseRequestFactory CruiseRequestFactory = (ICruiseRequestFactory)objectGiver.GiveObjectByType(typeof(ICruiseRequestFactory));
                IBuildNameFormatter BuildNameFormatter = (IBuildNameFormatter)objectGiver.GiveObjectByType(typeof(IBuildNameFormatter));
                ICruiseRequest request = CruiseRequestFactory.CreateCruiseRequest(cruiseRequest);

                if (!string.IsNullOrEmpty(request.ServerName))
                {
                    velocityContext["serverName"] = request.ServerName;
                    if (!string.IsNullOrEmpty(request.ProjectName))
                    {
                        velocityContext["projectName"] = request.ProjectName;
                        if (!string.IsNullOrEmpty(request.BuildName))
                            velocityContext["prettybuildName"] = BuildNameFormatter.GetPrettyBuildName(request.BuildSpecifier);
                    }
                }

                velocityContext["breadcrumbs"] = (((TopControlsViewBuilder) objectGiver.GiveObjectByType(typeof(TopControlsViewBuilder))).Execute()).ResponseFragment;
                velocityContext["sidebar"] = (((SideBarViewBuilder) objectGiver.GiveObjectByType(typeof(SideBarViewBuilder))).Execute()).ResponseFragment;
                velocityContext["mainContent"] = ((HtmlFragmentResponse) decoratedActionResponse).ResponseFragment;
                velocityContext["dashboardversion"] = GetVersion();

                return velocityViewGenerator.GenerateView("SiteTemplate.vm", velocityContext);
            }
            else
            {
                return decoratedActionResponse;
            }
        }
 public HttpResponseStreamWrapper(Stream stream, IRequest request)
 {
     this.OutputStream = stream;
     this.Request = request;
     this.Headers = new Dictionary<string, string>();
     this.Items = new Dictionary<string, object>();
 }
 bool IRequestHandler.OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request,
     bool isRedirect) {
     if (!frame.IsMain || CommonUrls.IsWithSixUrl(request.Url) || IsAuthUrl(new Uri(request.Url)))
         return false;
     OpenInSystemBrowser(request.Url);
     return true;
 }
        CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame,
            IRequest request, IRequestCallback callback) {
            if (CommonUrls.IsWithSixUrl(request.Url)) {
                var headers = request.Headers;
                headers[Common.ClientHeader] = DomainEvilGlobal.SecretData.UserInfo.ClientId.ToString();
                headers[Common.ClientHeaderV] = Common.App.ProductVersion;
                request.Headers = headers;
            }

            return CefReturnValue.Continue;
            //Example of how to set Referer
            // Same should work when setting any header
            // For this example only set Referer when using our custom scheme
            var url = new Uri(request.Url);
            if (url.Scheme == "customscheme") // CefSharpSchemeHandlerFactory.SchemeName
            {
                var headers = request.Headers;
                headers["Referer"] = "http://google.com";

                request.Headers = headers;
            }

            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed) {
                using (callback) {
                    if (request.Method == "POST") {
                        using (var postData = request.PostData) {
                            if (postData != null) {
                                var elements = postData.Elements;

                                var charSet = request.GetCharSet();

                                foreach (var element in elements) {
                                    if (element.Type == PostDataElementType.Bytes) {
                                        var body = element.GetBody(charSet);
                                    }
                                }
                            }
                        }
                    }

                    //Note to Redirect simply set the request Url
                    //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase))
                    //{
                    //    request.Url = "https://github.com/";
                    //}

                    //Callback in async fashion
                    //callback.Continue(true);
                    //return CefReturnValue.ContinueAsync;
                }
            }

            return CefReturnValue.Continue;
        }
예제 #16
0
        public override object GetResponse(IRequest httpReq, object request)
        {
            httpReq.RequestAttributes |= HandlerAttributes;
            var response = ExecuteService(request, httpReq);

            return response;
        }
예제 #17
0
        protected override void RenderOperation(System.Web.UI.HtmlTextWriter writer, IRequest httpReq, string operationName, string requestMessage, string responseMessage, string metadataHtml)
        {
            var operationControl = new Soap11OperationControl
            {
                HttpRequest = httpReq,
                MetadataConfig = HostContext.Config.ServiceEndpointsMetadataConfig,
                Title = HostContext.ServiceName,
                Format = this.Format,
                OperationName = operationName,
                HostName = httpReq.GetUrlHostName(),
                RequestMessage = requestMessage,
                ResponseMessage = responseMessage,
                MetadataHtml = metadataHtml,
            };
            if (!this.ContentType.IsNullOrEmpty())
            {
                operationControl.ContentType = this.ContentType;
            }
            if (!this.ContentFormat.IsNullOrEmpty())
            {
                operationControl.ContentFormat = this.ContentFormat;
            }

            operationControl.Render(writer);
        }
예제 #18
0
        public void Execute(TexImage image, IRequest request)
        {
            switch (request.Type)
            {
                case RequestType.ArrayCreation:
                    CreateArray(image, (ArrayCreationRequest)request);
                    break;
                case RequestType.ArrayExtraction:
                    Extract(image, (ArrayExtractionRequest)request);
                    break;
                case RequestType.ArrayUpdate:
                    Update(image, (ArrayUpdateRequest)request);
                    break;
                case RequestType.ArrayInsertion:
                    Insert(image, (ArrayInsertionRequest)request);
                    break;
                case RequestType.ArrayElementRemoval:
                    Remove(image, (ArrayElementRemovalRequest)request);
                    break;
                case RequestType.CubeCreation:
                    CreateCube(image, (CubeCreationRequest)request);
                    break;

                default:
                    Log.Error("ArrayTexLib can't handle this request: " + request.Type);
                    throw new TextureToolsException("ArrayTexLib can't handle this request: " + request.Type);
            }
        }
 private static void SetPolicyNames(IRequest request)
 {
     if (request.Parameters.Where(x => x.Key.StartsWith("PolicyNames", StringComparison.Ordinal)).ToList().Count == 0)
     {
         request.Parameters.Add("PolicyNames", "");
     }
 }
예제 #20
0
		public override void ProcessRequest(IRequest httpReq, IResponse httpRes, string operationName)
    	{
            if (!AssertAccess(httpReq, httpRes, httpReq.QueryString["op"])) return;

			var operationTypes = HostContext.Metadata.GetAllTypes();

    		if (httpReq.QueryString["xsd"] != null)
    		{
				var xsdNo = Convert.ToInt32(httpReq.QueryString["xsd"]);
                var schemaSet = XsdUtils.GetXmlSchemaSet(operationTypes);
    			var schemas = schemaSet.Schemas();
    			var i = 0; 
    			if (xsdNo >= schemas.Count)
    			{
    				throw new ArgumentOutOfRangeException("xsd");
    			}
    			httpRes.ContentType = "text/xml";
    			foreach (XmlSchema schema in schemaSet.Schemas())
    			{
    				if (xsdNo != i++) continue;
    				schema.Write(httpRes.OutputStream);
    				break;
    			}
    			return;
    		}

			using (var sw = new StreamWriter(httpRes.OutputStream))
			{
				var writer = new HtmlTextWriter(sw);
				httpRes.ContentType = "text/html";
				ProcessOperations(writer, httpReq, httpRes);
			}
    	}
        /// <summary>
        /// Non ASP.NET requests
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="operationName"></param>
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            if (string.IsNullOrEmpty(RelativeUrl) && string.IsNullOrEmpty(AbsoluteUrl))
                throw new ArgumentException("RelativeUrl and AbsoluteUrl is Required");

            if (!string.IsNullOrEmpty(AbsoluteUrl))
            {
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, this.AbsoluteUrl);
            }
            else
            {
                var absoluteUrl = request.GetApplicationUrl();
                if (!string.IsNullOrEmpty(RelativeUrl))
                {
                    if (this.RelativeUrl.StartsWith("/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl);
                    else if (this.RelativeUrl.StartsWith("~/"))
                        absoluteUrl = absoluteUrl.CombineWith(this.RelativeUrl.Replace("~/", ""));
                    else
                        absoluteUrl = request.AbsoluteUri.CombineWith(this.RelativeUrl);
                }
                response.StatusCode = (int)StatusCode;
                response.AddHeader(HttpHeaders.Location, absoluteUrl);
            }

            response.EndHttpHandlerRequest(skipClose: true);
        }
예제 #22
0
        /// <summary>
        /// Sends the specified request and returns a response.
        /// </summary>
        /// <param name="request">A <see cref="IRequest"/> that represents the HTTP request</param>
        /// <param name="cancellationToken">Used to cancel the request</param>
        /// <returns>A <see cref="Task" /> of <see cref="IResponse"/></returns>
        public async Task<IResponse> Send(IRequest request, CancellationToken cancellationToken)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            var httpOptions = CreateMessageHandler();
            httpOptions.AllowAutoRedirect = request.AllowAutoRedirect;

            if (httpOptions.SupportsAutomaticDecompression)
            {
                httpOptions.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            var http = new HttpClient(httpOptions)
            {
                BaseAddress = request.BaseAddress,
                Timeout = request.Timeout
            };
            using (var requestMessage = _messageBuilder.BuildRequestMessage(request))
            {
                // Make the request
                var responseMessage = await http.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, cancellationToken)
                    .ConfigureAwait(false);
                return await _messageBuilder.BuildResponse(responseMessage).ConfigureAwait(false);
            }
        }
     OnConnectedAsync(IRequest request, string connectionId)
 {
     _userCount += 1;
     Debug.WriteLine("OnConnectedAsync " + _userCount);
     this.Connection.Broadcast(_userCount);
     return base.OnConnectedAsync(request, connectionId);
 }
예제 #24
0
        public override void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration)
        {
            var requestType = requestDto != null ? requestDto.GetType() : null;

            if (ExcludeRequestType(requestType))
                return;

            using (var redis = redisManager.GetClient())
            {
                var redisLogEntry = redis.As<RequestLogEntry>();

                var entry = CreateEntry(request, requestDto, response, requestDuration, requestType);
                entry.Id = redisLogEntry.GetNextSequence();

                var key = UrnId.Create<RequestLogEntry>(entry.Id).ToLower();
                var nowScore = DateTime.UtcNow.ToUnixTime();

                using (var trans = redis.CreateTransaction())
                {
                    trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, key, nowScore));
                    trans.QueueCommand(r => r.Store(entry));

                    if (loggerCapacity != null)
                    {
                        trans.QueueCommand(r => r.RemoveRangeFromSortedSet(SortedSetKey, 0, -loggerCapacity.Value - 1));
                    }

                    trans.Commit();
                }
            }
        }
예제 #25
0
        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            ProcessInfo process;
            data = data ?? String.Empty;
            var shell = request.QueryString != null ? request.QueryString["shell"] : String.Empty;
            if (!_processes.TryGetValue(connectionId, out process) || process.Process.HasExited)
            {
                process = _processes.AddOrUpdate(connectionId, cId => StartProcess(cId, shell), (s, p) => StartProcess(s, shell));
            }
            else
            {
                if (data == "\x3")
                {
                    // If the user hit CTRL+C we sent the ^C character "\x3" from the client
                    // If the data is just ^C we then attach to the console and generate a CTRL_C signal (SIGINT)
                    CommandsNativeMethods.SetConsoleCtrlHandler(null, true);
                    CommandsNativeMethods.AttachConsole((uint)process.Process.Id);
                    CommandsNativeMethods.GenerateConsoleCtrlEvent(CommandsNativeMethods.ConsoleCtrlEvent.CTRL_C, 0);
                    Thread.Sleep(_cmdWaitTimeSpan);
                    CommandsNativeMethods.FreeConsole();
                    CommandsNativeMethods.SetConsoleCtrlHandler(null, false);
                }
                else
                {
                    //Both cmd.exe and powershell.exe are okay with either \r\n or \n for end-of-line.
                    process.Process.StandardInput.Write(data);
                    process.Process.StandardInput.Flush();
                }
                process.LastInputTime = DateTime.UtcNow;
            }

            return base.OnReceived(request, connectionId, data);
        }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            var authErrorMessage = "";
            try
            {
                // Perform security check
                if (CanExecute(req))
                    return;
            }
            catch (System.Exception ex)
            {
                authErrorMessage = ex.Message;
                var message = string.Format("Blocked unauthorized request: {0} {1} by ip = {2} due to {3}",
                    req.Verb,
                    req.AbsoluteUri,
                    req.UserHostAddress ?? "unknown",
                    authErrorMessage);
                Log.Error(message);
            }

            // Security failed!
            var responseMessage = "You are not authorized. " + authErrorMessage;

            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            res.StatusDescription = responseMessage;
            res.AddHeader(HttpHeaders.WwwAuthenticate, string.Format("{0} realm=\"{1}\"", "", "custom api"));
            res.ContentType = "text/plain";
            res.Write(responseMessage);
            res.Close();
        }
예제 #27
0
 private void WriteRequestBody(IRequest request)
 {
     lock (thisLock)
     {
         File.WriteAllText(Environment.GetEnvironmentVariable("directory") + request.Resource, request.Body);
     }
 }
예제 #28
0
        CefReturnValue IRequestHandler.OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
            using (callback)
            {
                if (request.Method == "POST")
                {
                    using (var postData = request.PostData)
                    {
                        var elements = postData.Elements;

                        var charSet = request.GetCharSet();

                        foreach (var element in elements)
                        {
                            if (element.Type == PostDataElementType.Bytes)
                            {
                                var body = element.GetBody(charSet);
                            }
                        }
                    }
                }

                //Note to Redirect simply set the request Url
                //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase))
                //{
                //    request.Url = "https://github.com/";
                //}

                //Callback in async fashion
                //callback.Continue(true);
                //return CefReturnValue.ContinueAsync;
            }
            
            return CefReturnValue.Continue;
        }
예제 #29
0
		internal static string PrettyPrintEndpoint(IRequest request, string endpoint)
		{
			var pretty = ReplaceParams.Replace(endpoint, (m) =>
			{
				var key = m.Groups[1].Value.ToLowerInvariant();
				switch(key)
				{
					case "index" :  return PrettyParam(key, request.RouteValues.Index);
					case "name" :  return PrettyParam(key, request.RouteValues.Name);
					case "feature" :  return PrettyParam(key, request.RouteValues.Feature);
					case "field" :  return PrettyParam(key, request.RouteValues.Field);
					case "fields" :  return PrettyParam(key, request.RouteValues.Fields);
					case "id" :  return PrettyParam(key, request.RouteValues.Id);
					case "index_metric" :  return PrettyParam(key, request.RouteValues.IndexMetric);
					case "lang" :  return PrettyParam(key, request.RouteValues.Lang);
					case "metric" :  return PrettyParam(key, request.RouteValues.Metric);
					case "node_id" :  return PrettyParam(key, request.RouteValues.NodeId);
					case "repository" :  return PrettyParam(key, request.RouteValues.Repository);
					case "scroll_id" :  return PrettyParam(key, request.RouteValues.ScrollId);
					case "snapshot" :  return PrettyParam(key, request.RouteValues.Snapshot);
					case "type" :  return PrettyParam(key, request.RouteValues.Type);
					default:  return PrettyParam(key, "<Unknown route variable>");
				}
			});
			return pretty;
		}
예제 #30
0
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            response.ContentType = "text/plain";
            response.StatusCode = 403;

		    response.EndHttpHandlerRequest(skipClose: true, afterBody: r => {
                r.Write("Forbidden\n\n");

                r.Write("\nRequest.HttpMethod: " + request.Verb);
                r.Write("\nRequest.PathInfo: " + request.PathInfo);
                r.Write("\nRequest.QueryString: " + request.QueryString);

                if (HostContext.Config.DebugMode)
                {
                    r.Write("\nRequest.RawUrl: " + request.RawUrl);

                    if (IsIntegratedPipeline.HasValue)
                        r.Write("\nApp.IsIntegratedPipeline: " + IsIntegratedPipeline);
                    if (!WebHostPhysicalPath.IsNullOrEmpty())
                        r.Write("\nApp.WebHostPhysicalPath: " + WebHostPhysicalPath);
                    if (!WebHostRootFileNames.IsEmpty())
                        r.Write("\nApp.WebHostRootFileNames: " + TypeSerializer.SerializeToString(WebHostRootFileNames));
                    if (!WebHostUrl.IsNullOrEmpty())
                        r.Write("\nApp.WebHostUrl: " + WebHostUrl);
                    if (!DefaultRootFileName.IsNullOrEmpty())
                        r.Write("\nApp.DefaultRootFileName: " + DefaultRootFileName);
                    if (!DefaultHandler.IsNullOrEmpty())
                        r.Write("\nApp.DefaultHandler: " + DefaultHandler);
                    if (!HttpHandlerFactory.DebugLastHandlerArgs.IsNullOrEmpty())
                        r.Write("\nApp.DebugLastHandlerArgs: " + HttpHandlerFactory.DebugLastHandlerArgs);
                }
            });
		}
예제 #31
0
 public static bool ApplyResponseFilters(IRequest httpReq, IResponse httpRes, object response)
 {
     return(AssertAppHost().ApplyResponseFilters(httpReq, httpRes, response));
 }
예제 #32
0
 public static object RaiseServiceException(IRequest httpReq, object request, Exception ex)
 {
     return(AssertAppHost().OnServiceException(httpReq, request, ex));
 }
예제 #33
0
 public static IVirtualNode ResolveVirtualNode(string virtualPath, IRequest httpReq)
 {
     return(AssertAppHost().ResolveVirtualNode(virtualPath, httpReq));
 }
예제 #34
0
 public static IVirtualDirectory ResolveVirtualDirectory(string virtualPath, IRequest httpReq)
 {
     return(AssertAppHost().ResolveVirtualDirectory(virtualPath, httpReq));
 }
예제 #35
0
 public static string ResolvePhysicalPath(string virtualPath, IRequest httpReq)
 {
     return(AssertAppHost().ResolvePhysicalPath(virtualPath, httpReq));
 }
예제 #36
0
 public static string ResolveAbsoluteUrl(string virtualPath, IRequest httpReq)
 {
     return(AssertAppHost().ResolveAbsoluteUrl(virtualPath, httpReq));
 }
예제 #37
0
 public static string ResolveLocalizedString(string text, IRequest request = null)
 {
     return(AssertAppHost().ResolveLocalizedString(text, request));
 }
예제 #38
0
 /*----------------------------------------------------------------------------------------*/
 /// <summary>
 /// Gets the interceptor associated with the advice for the specified request.
 /// </summary>
 /// <param name="request">The request in question.</param>
 /// <returns>The interceptor.</returns>
 public IInterceptor GetInterceptor(IRequest request)
 {
     return(Interceptor ?? Callback(request));
 }
예제 #39
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var namespaces = Config.GetDefaultNamespaces(metadata);

            metadata.RemoveIgnoredTypesForNet(Config);

            if (Config.GlobalNamespace == null)
            {
                metadata.Types.Each(x => namespaces.Add(x.Namespace));
                metadata.Operations.Each(x => {
                    namespaces.Add(x.Request.Namespace);
                    if (x.Response != null)
                    {
                        namespaces.Add(x.Response.Namespace);
                    }
                });
            }
            else
            {
                namespaces.Add(Config.GlobalNamespace);
            }

            string DefaultValue(string k) => request.QueryString[k].IsNullOrEmpty() ? "'''" : "'";

            var sbInner = new StringBuilder();
            var sb      = new StringBuilderWrapper(sbInner);

            sb.AppendLine("' Options:");
            sb.AppendLine("'Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("'Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("'Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("''")));
            sb.AppendLine("'BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine("'");
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(DefaultValue("GlobalNamespace"), Config.GlobalNamespace));
            sb.AppendLine("{0}MakePartial: {1}".Fmt(DefaultValue("MakePartial"), Config.MakePartial));
            sb.AppendLine("{0}MakeVirtual: {1}".Fmt(DefaultValue("MakeVirtual"), Config.MakeVirtual));
            sb.AppendLine("{0}MakeDataContractsExtensible: {1}".Fmt(DefaultValue("MakeDataContractsExtensible"), Config.MakeDataContractsExtensible));
            sb.AppendLine("{0}AddReturnMarker: {1}".Fmt(DefaultValue("AddReturnMarker"), Config.AddReturnMarker));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(DefaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}AddDataContractAttributes: {1}".Fmt(DefaultValue("AddDataContractAttributes"), Config.AddDataContractAttributes));
            sb.AppendLine("{0}AddIndexesToDataMembers: {1}".Fmt(DefaultValue("AddIndexesToDataMembers"), Config.AddIndexesToDataMembers));
            sb.AppendLine("{0}AddGeneratedCodeAttributes: {1}".Fmt(DefaultValue("AddGeneratedCodeAttributes"), Config.AddGeneratedCodeAttributes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(DefaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(DefaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(DefaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}ExportValueTypes: {1}".Fmt(DefaultValue("ExportValueTypes"), Config.ExportValueTypes));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(DefaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(", ")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(DefaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(", ")));
            sb.AppendLine("{0}AddNamespaces: {1}".Fmt(DefaultValue("AddNamespaces"), Config.AddNamespaces.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}AddDefaultXmlNamespace: {1}".Fmt(DefaultValue("AddDefaultXmlNamespace"), Config.AddDefaultXmlNamespace));
            sb.AppendLine();

            namespaces.Where(x => !string.IsNullOrEmpty(x))
            .Each(x => sb.AppendLine("Imports {0}".Fmt(x)));
            if (Config.AddGeneratedCodeAttributes)
            {
                sb.AppendLine("Imports System.CodeDom.Compiler");
            }

            if (Config.AddDataContractAttributes &&
                Config.AddDefaultXmlNamespace != null)
            {
                sb.AppendLine();

                namespaces.Where(x => !Config.DefaultNamespaces.Contains(x)).ToList()
                .ForEach(x =>
                         sb.AppendLine("<Assembly: ContractNamespace(\"{0}\", ClrNamespace:=\"{1}\")>"
                                       .Fmt(Config.AddDefaultXmlNamespace, x)));
            }

            sb.AppendLine();

            sb.AppendLine("Namespace Global");
            sb = sb.Indent();

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            allTypes = new List <MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);

            var orderedTypes = allTypes
                               .OrderBy(x => x.Namespace)
                               .ThenBy(x => x.Name)
                               .ToList();

            orderedTypes = FilterTypes(orderedTypes);

            foreach (var type in orderedTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        if (requestTypesMap.TryGetValue(type, out var operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions
                        {
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    !type.ReturnVoidMarker &&
                                    type.ReturnMarkerTypeName == null)
                                {
                                    return(null);
                                }

                                if (type.ReturnVoidMarker)
                                {
                                    return("IReturnVoid");
                                }
                                if (type.ReturnMarkerTypeName != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) }));
                                }
                                return(response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                            new CreateTypeOptions {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS, allTypes,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (lastNS != null)
            {
                sb.AppendLine("End Namespace");
            }

            sb = sb.UnIndent();
            sb.AppendLine("End Namespace");

            sb.AppendLine();

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }
예제 #40
0
        public override void ProcessRequest(IRequest request, IResponse response, string operationName)
        {
            HostContext.ApplyCustomHandlerRequestFilters(request, response);
            if (response.IsClosed)
            {
                return;
            }

            response.EndHttpHandlerRequest(afterHeaders: r =>
            {
                var node = this.VirtualNode ?? request.GetVirtualNode();
                var file = node as IVirtualFile;
                if (file == null)
                {
                    var dir = node as IVirtualDirectory;
                    if (dir != null)
                    {
                        file = dir.GetDefaultDocument();
                        if (file != null && HostContext.Config.RedirectToDefaultDocuments)
                        {
                            r.Redirect(request.GetPathUrl() + '/' + file.Name);
                            return;
                        }
                    }

                    if (file == null)
                    {
                        var fileName         = request.PathInfo;
                        var originalFileName = fileName;

                        if (Env.IsMono)
                        {
                            //Create a case-insensitive file index of all host files
                            if (allFiles == null)
                            {
                                allFiles = CreateFileIndex(HostContext.VirtualFileSources.RootDirectory.RealPath);
                            }
                            if (allDirs == null)
                            {
                                allDirs = CreateDirIndex(HostContext.VirtualFileSources.RootDirectory.RealPath);
                            }

                            if (allFiles.TryGetValue(fileName.ToLower(), out fileName))
                            {
                                file = HostContext.VirtualFileSources.GetFile(fileName);
                            }
                        }

                        if (file == null)
                        {
                            var msg = ErrorMessages.FileNotExistsFmt.Fmt(request.PathInfo);
                            log.Warn($"{msg} in path: {originalFileName}");
                            response.StatusCode        = 404;
                            response.StatusDescription = msg;
                            return;
                        }
                    }
                }

                file.Refresh(); //refresh FileInfo, DateModified, Length

                TimeSpan maxAge;
                if (r.ContentType != null && HostContext.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge))
                {
                    r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds);
                }

                if (request.HasNotModifiedSince(file.LastModified))
                {
                    r.ContentType       = MimeTypes.GetMimeType(file.Name);
                    r.StatusCode        = (int)HttpStatusCode.NotModified;
                    r.StatusDescription = HttpStatusCode.NotModified.ToString();
                    return;
                }

                try
                {
                    var encoding       = request.GetCompressionType();
                    var shouldCompress = encoding != null && HostContext.AppHost.ShouldCompressFile(file);
                    r.AddHeaderLastModified(file.LastModified);
                    r.ContentType = MimeTypes.GetMimeType(file.Name);

                    if (ResponseFilter != null)
                    {
                        ResponseFilter(request, r, file);

                        if (r.IsClosed)
                        {
                            return;
                        }
                    }

                    if (!HostContext.DebugMode && file.VirtualPath.EqualsIgnoreCase(DefaultFilePath))
                    {
                        if (file.LastModified > DefaultFileModified)
                        {
                            SetDefaultFile(DefaultFilePath, file.ReadAllBytes(), file.LastModified); //reload
                        }
                        if (!shouldCompress)
                        {
                            r.OutputStream.Write(DefaultFileContents, 0, DefaultFileContents.Length);
                        }
                        else
                        {
                            byte[] zipBytes = null;
                            if (encoding == CompressionTypes.GZip)
                            {
                                zipBytes = DefaultFileContentsGzip ??
                                           (DefaultFileContentsGzip = DefaultFileContents.CompressBytes(encoding));
                            }
                            else if (encoding == CompressionTypes.Deflate)
                            {
                                zipBytes = DefaultFileContentsDeflate ??
                                           (DefaultFileContentsDeflate = DefaultFileContents.CompressBytes(encoding));
                            }
                            else
                            {
                                zipBytes = DefaultFileContents.CompressBytes(encoding);
                            }
                            r.AddHeader(HttpHeaders.ContentEncoding, encoding);
                            r.SetContentLength(zipBytes.Length);
                            r.OutputStream.Write(zipBytes, 0, zipBytes.Length);
                            r.OutputStream.Flush();
                        }

                        r.Close();
                        return;
                    }

                    if (HostContext.Config.AllowPartialResponses)
                    {
                        r.AddHeader(HttpHeaders.AcceptRanges, "bytes");
                    }
                    long contentLength = file.Length;
                    long rangeStart, rangeEnd;
                    var rangeHeader = request.Headers[HttpHeaders.Range];
                    if (HostContext.Config.AllowPartialResponses && rangeHeader != null)
                    {
                        rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd);

                        if (rangeEnd > contentLength - 1)
                        {
                            rangeEnd = contentLength - 1;
                        }

                        r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength);
                    }
                    else
                    {
                        rangeStart = 0;
                        rangeEnd   = contentLength - 1;
                    }
                    var outputStream = r.OutputStream;
                    using (var fs = file.OpenRead())
                    {
                        if (rangeStart != 0 || rangeEnd != file.Length - 1)
                        {
                            fs.WritePartialTo(outputStream, rangeStart, rangeEnd);
                        }
                        else
                        {
                            if (!shouldCompress)
                            {
                                r.SetContentLength(contentLength);
                                fs.CopyTo(outputStream, BufferSize);
                                outputStream.Flush();
                            }
                            else
                            {
                                r.AddHeader(HttpHeaders.ContentEncoding, encoding);
                                outputStream = outputStream.CompressStream(encoding);
                                fs.CopyTo(outputStream);
                                outputStream.Flush();
                                outputStream.Close();
                            }
                        }
                    }
                }
#if !NETSTANDARD1_6
                catch (System.Net.HttpListenerException ex)
                {
                    if (ex.ErrorCode == 1229)
                    {
                        return;
                    }
                    //Error: 1229 is "An operation was attempted on a nonexistent network connection"
                    //This exception occures when http stream is terminated by web browser because user
                    //seek video forward and new http request will be sent by browser
                    //with attribute in header "Range: bytes=newSeekPosition-"
                    throw;
                }
#endif
                catch (Exception ex)
                {
                    log.ErrorFormat($"Static file {request.PathInfo} forbidden: {ex.Message}");
                    throw new HttpException(403, "Forbidden.");
                }
            });
        }
예제 #41
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="request"></param>
 /// <typeparam name="TResponse"></typeparam>
 /// <returns></returns>
 protected Task <TResponse> SendAsync <TResponse>(IRequest <TResponse> request)
 {
     return(Mediator.Send(request));
 }
예제 #42
0
 /*----------------------------------------------------------------------------------------*/
 #region Public Methods
 /// <summary>
 /// Determines whether the advice matches the specified request.
 /// </summary>
 /// <param name="request">The request in question.</param>
 /// <returns><see langword="True"/> if the request matches, otherwise <see langword="false"/>.</returns>
 public bool Matches(IRequest request)
 {
     return(IsDynamic ? Condition.Matches(request) : request.Method.GetMethodHandle().Equals(MethodHandle));
 }
예제 #43
0
        public override Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName)
        {
            try
            {
                var appHost = HostContext.AppHost;
                if (appHost.ApplyPreRequestFilters(httpReq, httpRes))
                {
                    return(TypeConstants.EmptyTask);
                }

                var restPath = GetRestPath(httpReq.Verb, httpReq.PathInfo);
                if (restPath == null)
                {
                    return(new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo)
                           .AsTaskException());
                }
                httpReq.SetRoute(restPath as RestPath);

                operationName = restPath.RequestType.GetOperationName();

                var callback = httpReq.GetJsonpCallback();
                var doJsonp  = HostContext.Config.AllowJsonpRequests &&
                               !string.IsNullOrEmpty(callback);

                if (ResponseContentType != null)
                {
                    httpReq.ResponseContentType = ResponseContentType;
                }

                var responseContentType = httpReq.ResponseContentType;
                appHost.AssertContentType(responseContentType);

                var request = httpReq.Dto = CreateRequest(httpReq, restPath);

                if (appHost.ApplyRequestFilters(httpReq, httpRes, request))
                {
                    return(TypeConstants.EmptyTask);
                }

                var rawResponse = GetResponse(httpReq, request);

                if (httpRes.IsClosed)
                {
                    return(TypeConstants.EmptyTask);
                }

                return(HandleResponse(rawResponse, response =>
                {
                    response = appHost.ApplyResponseConverters(httpReq, response);

                    if (appHost.ApplyResponseFilters(httpReq, httpRes, response))
                    {
                        return TypeConstants.EmptyTask;
                    }

                    if (responseContentType.Contains("jsv") && !string.IsNullOrEmpty(httpReq.QueryString[Keywords.Debug]))
                    {
                        return WriteDebugResponse(httpRes, response);
                    }

                    if (doJsonp && !(response is CompressedResult))
                    {
                        return httpRes.WriteToResponse(httpReq, response, (callback + "(").ToUtf8Bytes(), ")".ToUtf8Bytes());
                    }

                    return httpRes.WriteToResponse(httpReq, response);
                },
                                      ex => !HostContext.Config.WriteErrorsToResponse
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq))));
            }
            catch (Exception ex)
            {
                return(!HostContext.Config.WriteErrorsToResponse
                    ? ex.ApplyResponseConverters(httpReq).AsTaskException()
                    : HandleException(httpReq, httpRes, operationName, ex.ApplyResponseConverters(httpReq)));
            }
        }
예제 #44
0
 public override void DisposeFeedback(IRequest request, IFigure feedback)
 {
 }
예제 #45
0
 public override void OnEndRequest(IRequest request = null)
 {
     base.OnEndRequest(request);
 }
예제 #46
0
 public override void OnRegistered(IRequest httpReq, IAuthSession session, IServiceBase service)
 {
     "OnRegistered()".Print();
 }
예제 #47
0
 public override void Execute(IRequest req, IResponse res, object requestDto)
 {
     ((RuntimeAttributes)requestDto).Id++;
 }
예제 #48
0
        public static object CreateRequest(IRequest httpReq, IRestPath restPath, Dictionary <string, string> requestParams)
        {
            var requestDto = CreateContentTypeRequest(httpReq, restPath.RequestType, httpReq.ContentType);

            return(CreateRequest(httpReq, restPath, requestParams, requestDto));
        }
예제 #49
0
 public bool CanResolve(IRequest request)
 {
     return(_parent.CanResolve(request));
 }
 protected string CalculateContentHash <T>(IRequest <T> request)
 {
     throw new NotImplementedException();
 }
예제 #51
0
 /*----------------------------------------------------------------------------------------*/
 /// <summary>
 /// Creates the interceptor associated with the attribute.
 /// </summary>
 /// <param name="request">The request that is being intercepted.</param>
 /// <returns>The interceptor.</returns>
 public abstract IInterceptor CreateInterceptor(IRequest request);
예제 #52
0
 public IEnumerable <object> Resolve(IRequest request)
 {
     return(_parent.Resolve(request));
 }
예제 #53
0
 /**
  * Convert request parameters to Url encoded query string
  */
 internal static string GetParametersAsString(IRequest request)
 {
     return(GetParametersAsString(request.ParameterCollection));
 }
        /// <summary>
        /// Called before a resource is loaded. To specify a handler for the resource return a <see cref="ResourceHandler"/> object
        /// </summary>
        /// <param name="browserControl">The browser UI control</param>
        /// <param name="browser">the browser object</param>
        /// <param name="frame">the frame object</param>
        /// <param name="request">the request object - cannot be modified in this callback</param>
        /// <returns>To allow the resource to load normally return NULL otherwise return an instance of ResourceHandler with a valid stream</returns>
        public virtual IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
        {
            try
            {
                LegacyResourceHandlerFactoryItem entry;

                if (Handlers.TryGetValue(request.Url, out entry))
                {
                    if (entry.OneTimeUse)
                    {
                        Handlers.TryRemove(request.Url, out entry);
                    }

                    return(entry.Handler);
                }

                return(null);
            }
            finally
            {
                request.Dispose();
            }
        }
 protected override int DefaultDelete <T>(IRequest <T> request) => StarcounterOperations <T> .Delete(request);
 public override Task <object> HandleExceptionAsync(IRequest request, T requestDto, System.Exception ex)
 {
     return(DtoUtils.CreateErrorResponse(requestDto, ex).InTask());
 }
 protected override IEnumerable <T> DefaultSelect <T>(IRequest <T> request) => StarcounterOperations <T> .Select(request);
예제 #58
0
 void IConnection.PrepareRequest(IRequest request)
 {
     // PORT: Previously, this string differed based on the platform the app was running on (NET4, NET45,, etc.). Now it will always be NetStadnard.
     request.UserAgent = CreateUserAgentString("SignalR.Client.NetStandard");
     request.SetRequestHeaders(Headers);
 }
        public override void Execute(IRequest req, IResponse res, object requestDto)
        {
            if (req.Verb != HttpMethods.Get && req.Verb != HttpMethods.Head)
            {
                return;
            }
            if (req.IsInProcessRequest())
            {
                return;
            }

            var feature = HostContext.GetPlugin <HttpCacheFeature>();

            if (feature == null)
            {
                throw new NotSupportedException(ErrorMessages.CacheFeatureMustBeEnabled.Fmt("[CacheResponse]"));
            }

            var keyBase   = "res:" + req.RawUrl;
            var keySuffix = MimeTypes.GetExtension(req.ResponseContentType);

            var modifiers = "";

            if (req.ResponseContentType == MimeTypes.Json)
            {
                string jsonp = req.GetJsonpCallback();
                if (jsonp != null)
                {
                    modifiers = "jsonp:" + jsonp.SafeVarName();
                }
            }

            if (VaryByUser)
            {
                modifiers += (modifiers.Length > 0 ? "+" : "") + "user:"******"+" : "") + "role:" + role;
                            }
                        }
                    }
                }
            }

            if (modifiers.Length > 0)
            {
                keySuffix += "+" + modifiers;
            }

            var cacheInfo = new CacheInfo
            {
                KeyBase      = keyBase,
                KeyModifiers = keySuffix,
                ExpiresIn    = Duration > 0 ? TimeSpan.FromSeconds(Duration) : (TimeSpan?)null,
                MaxAge       = MaxAge >= 0 ? TimeSpan.FromSeconds(MaxAge) : (TimeSpan?)null,
                CacheControl = CacheControl,
                VaryByUser   = VaryByUser,
                LocalCache   = LocalCache,
            };

            if (req.HandleValidCache(cacheInfo))
            {
                return;
            }

            req.Items[Keywords.CacheInfo] = cacheInfo;
        }
 protected override int DefaultInsert <T>(IRequest <T> request) => StarcounterOperations <T> .Insert(request);