public UserService(CaffStoreDbContext context, IHttpRequestContext requestContext, UserManager <User> userManager, IMapper mapper) { _context = context; _requestContext = requestContext; _userManager = userManager; _mapper = mapper; }
public CaffItemService(CaffStoreDbContext context, IHttpRequestContext requestContext, IFileService fileService, IMapper mapper) { _context = context; _requestContext = requestContext; _fileService = fileService; _mapper = mapper; }
public HttpRequestResponseContext(IHttpRequestContext requestState, HttpListenerResponse response) { HostContext = requestState.HostContext; Request = requestState.Request; User = requestState.User; Response = response; }
/// <summary> /// /// </summary> /// <param name="context"></param> public byte[] ProcessRequest(IHttpRequestContext context) { ResponseType = ResponseType.Json; ResponseFormater = new JsonResponseFormater(); var body = new ResponseBody(); OnRequest(context, body); return ProcessResponse(context, body); }
public async Task <HttpResponseMessage> Delete(string requestUri, IHttpRequestContext context = null) { var builder = new HttpRequestBuilder() .AddMethod(HttpMethod.Delete) .AddRequestUri(requestUri); builder = HttpRequestBuilder.BuildRequestFromContext(builder, context); return(await builder.SendAsync()); }
/// <summary> /// /// </summary> /// <param name="context"></param> public byte[] ProcessRequest(IHttpRequestContext context) { ResponseType = ResponseType.Json; ResponseFormater = new JsonResponseFormater(); var body = new ResponseBody(); OnRequest(context, body); return(ProcessResponse(context, body)); }
public HttpRequestContextTests() { var logger = Substitute.For <ILogger>(); _httpRequestContext = new HttpRequestContext { Request = new MockHttpRequest(), Logger = logger }; }
public async Task <HttpResponseMessage> Put(string requestUri, object value, IHttpRequestContext context = null) { var builder = new HttpRequestBuilder() .AddMethod(HttpMethod.Put) .AddRequestUri(requestUri) .AddContent(new JsonContent(value)); builder = HttpRequestBuilder.BuildRequestFromContext(builder, context); return(await builder.SendAsync()); }
public JwtTokenValidatorTests() { _httpRequestContext = Substitute.For <IHttpRequestContext>(); _httpRequestContext.Security.Returns(x => _security); var distributedCache = Substitute.For <IDistributedCache>(); distributedCache.GetAsync(Arg.Any <string>()).Returns(Task.FromResult((byte[])null)); _cacheManager = new CacheManager(distributedCache); }
public GraphQlDomain(ISchema schema, IDocumentExecuter documentExecuter, IConfiguration configuration, ILogger logger, IHttpRequestContext requestContext, IGraphRequestContext graphRequestContext, IEnumerable <IValidationRule> validationRules) { _schema = schema; _documentExecuter = documentExecuter; _configuration = configuration; _logger = logger; _requestContext = requestContext; _graphRequestContext = graphRequestContext; _validationRules = validationRules; }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task <IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode = 200; string page = (context.Request.RawUrl ?? "").Split('?')[0].ToLower(); byte[] result; if (PageListen.ContainsKey(page)) { var func = PageListen[page]; result = func(context); return(new ByteResponse(statusCode, "OK", result)); } return(new ByteResponse(404, "Not found", Encoding.UTF8.GetBytes(""))); }
public async Task <IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode; RequestPackage package; var actionDispatcher = GameEnvironment.Setting.ActionDispatcher; if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode)) { return(new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0])); } GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request); session.ProxySid = package.ProxySid; } else { session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request); } package.Bind(session); ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session); if (package.IsUrlParam) { httpGet["UserHostAddress"] = session.RemoteAddress; httpGet["ssid"] = session.KeyCode.ToString("N"); httpGet["http"] = "1"; } var result = await System.Threading.Tasks.Task.Run <byte[]>(() => { try { return(ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet)); } catch (Exception ex) { TraceLog.WriteError("Excute mainclass error:{0}", ex); return(new byte[0]); } }); return(new ByteResponse(statusCode, "OK", result)); }
public RequestStarting(IHttpRequestContext context, out dynamic ctx) { RequestContext = new { CorrelationId = Guid.NewGuid(), context.Path, context.Host, context.IsHttps, context.Method, context.Headers }; ctx = RequestContext; Timestamp = DateTimeOffset.Now.ToString(Constants.DateTimeOffsetFormat); }
protected override void OnRequest(IHttpRequestContext context, ResponseBody body) { var watch = Stopwatch.StartNew(); try { string param; if (CheckSign(context, out param)) { HandlerData handlerData; if (TryUrlQueryParse(param, out handlerData)) { body.Handler = handlerData.Name; body.Data = HandlerManager.Excute(handlerData); } else { body.StateCode = StateCode.NoHandler; body.StateDescription = StateDescription.NoHandler; } } else { body.StateCode = StateCode.SignError; body.StateDescription = StateDescription.SignError;//"Sign error."; } } catch (HandlerException handlerError) { body.StateCode = handlerError.StateCode; body.StateDescription = handlerError.Message; TraceLog.WriteError("Request handle error:{0}", handlerError); } catch (Exception error) { body.StateCode = StateCode.Error; body.StateDescription = StateDescription.Error;// "Process request fail."; TraceLog.WriteError("Request handle error:{0}", error); } var ms = watch.ElapsedMilliseconds; if (ms > 20) { TraceLog.Write("Request timeout:{0}ms", ms); } }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="param"></param> /// <returns></returns> protected virtual bool CheckSign(IHttpRequestContext context, out string param) { param = null; string query; string sign; if ("POST".Equals(context.Request.HttpMethod)) { string postString; using (var read = new StreamReader(context.Request.InputStream)) { postString = read.ReadToEnd(); } var signIdx = postString.IndexOf("sign=", StringComparison.InvariantCultureIgnoreCase); if (signIdx == -1) { return(false); } param = postString.Substring(0, signIdx - 1); sign = signIdx + 5 < postString.Length ? postString.Substring(signIdx + 5) : ""; } else { sign = context.Request.QueryString["sign"]; if (string.IsNullOrEmpty(sign)) { return(false); } query = context.Request.Url.Query.Substring(1); var signIdx = query.IndexOf("sign", StringComparison.InvariantCultureIgnoreCase); if (signIdx == -1) { return(false); } param = query.Substring(0, signIdx - 1); } var mysign = CryptoHelper.MD5_Encrypt(param + HandlerManager.SignKey, Encoding.UTF8); return(String.Compare(sign, mysign, StringComparison.OrdinalIgnoreCase) == 0); }
public async Task <IHarvestRequestResult> MakeRequest(string url, IHttpRequestContext ctx, bool isretry = false) { var requestTimer = new Stopwatch(); requestTimer.Start(); HtmlDocument doc = null; try { _logger.LogDebug(string.Format("Making web request: {0}", url)); InitialiseCertificates(); using (var resp = await _httpManager.Get(url, ctx)) { doc = new HtmlDocument(); doc.LoadHtml((await resp.Content.ReadAsStringAsync()).Trim()); if (doc.DocumentNode.InnerText.Contains("Request unsuccessful")) { _logger.LogError(string.Format("Incapsula request recieved!")); throw new Exception("Request did not fail but reurned an Incapsula request!"); } _logger.LogDebug(string.Format("Web request response successfully recieved & serialised to cache: {0}bytes", doc.DocumentNode.OuterLength)); } LastRequestFailed = false; } catch (Exception ex) { LastRequestFailed = true; _logger.LogDebug(string.Format("Web request failed as follows: {0}", ex.Message)); _logger.LogDebug(string.Format("Web request was cancelled & failed to complete: {0}", url)); throw ex; } await ApplyRequestThrottle(requestTimer); return(new HarvestRequestResult() { InnerHtml = doc.DocumentNode.InnerHtml, InnerText = doc.DocumentNode.InnerText }); }
public async Task<IHttpResponseAction> Execute(IHttpRequestContext state) { var baseUri = new Uri(state.Request.Url.Scheme + "://" + state.Request.Url.Authority); // Find a handler matched by URI HandlerDelegate handler = null; UriTemplateMatch uriMatch = null; foreach (var i in _uriHandlers) { var match = i.UriTemplate.Match(baseUri, state.Request.Url); if (match != null) { handler = i.Handler; uriMatch = match; break; } } if (handler == null) { var r = new ContentResponse(400, "Cannot find handler", ""); return r; } // Handle request try { var r = await handler(state, uriMatch); return r; } catch (Exception e) { var r = new ContentResponse(500, "", "Error!\n" + e); return r; } }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task <IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode; RequestPackage package; var actionDispatcher = GameEnvironment.Setting.ActionDispatcher; if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode)) { return(new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0])); } GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request); session.ProxySid = package.ProxySid; } else { session = (string.IsNullOrEmpty(package.SessionId) ? GameSession.GetSessionByCookie(context.Request) : GameSession.Get(package.SessionId)) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request); } session.InitHttp(context.Request); session.RemoteAddress = context.UserHostAddress; package.Bind(session); ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session); if (package.IsUrlParam) { httpGet["UserHostAddress"] = session.RemoteAddress; httpGet["ssid"] = session.KeyCode.ToString("N"); httpGet["http"] = "1"; } var result = await System.Threading.Tasks.Task.Run <byte[]>(() => { try { return(ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet)); } catch (Exception ex) { TraceLog.WriteError("Excute mainclass error:{0}", ex); return(new byte[0]); } }); string sessionId = session.SessionId; var response = new ByteResponse(statusCode, "OK", result, session.UserId.ToString()) { RequestParams = package.OriginalParam }; response.CookieHandle += ctx => { var cookie = ctx.Request.Cookies["sid"]; if (cookie == null) { cookie = new Cookie("sid", sessionId); cookie.Expires = DateTime.Now.AddMinutes(5); ctx.Response.SetCookie(cookie); } }; return(response); }
public MyRequestScope(IMyHttpLogger httpLogger, IHttpRequestContext httpRequestContext) { httpLogger.LogMessage("Creating a new instance of MyRequestScope"); Id = httpRequestContext.Request.Headers["X-SomeKey"]; httpLogger.LogMessage($"Setting: {Id}"); }
public async Task Delete <T>(string url, IHttpRequestContext context = null) { await Delete(url); }
private static byte[] OnService(IHttpRequestContext context) { return new MyHttpHandler().ProcessRequest(context); }
/// <summary> /// /// </summary> /// <see cref="IHttpModule.HandleRequest(IHttpRequestContext)" /> public IHttpModuleHandleRequestResult HandleRequest(IHttpRequestContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpModuleHandleRequestResult result = new HttpModuleHandleRequestResult(); result.RequestContext = context; try { BeforeHandleRequestContext beforeHandleCtx = new BeforeHandleRequestContext(); { beforeHandleCtx.Http = context; beforeHandleCtx.InvokeAfterHandleRequest = true; beforeHandleCtx.InvokeHandleRequest = true; this.OnBeforeHandleRequest(beforeHandleCtx); } HandleRequestContext handleCtx = new HandleRequestContext(); bool requestWasHandled = false; { handleCtx.Http = context; handleCtx.InvokeAfterHandleRequest = beforeHandleCtx.InvokeAfterHandleRequest; if (beforeHandleCtx.InvokeHandleRequest) { this.OnHandleRequest(handleCtx); requestWasHandled = true; } } if (handleCtx.InvokeAfterHandleRequest) { AfterHandleRequestContext afterHandleCtx = new AfterHandleRequestContext(); afterHandleCtx.RequestWasHandled = requestWasHandled; { afterHandleCtx.Http = context; this.OnAfterHandleRequest(afterHandleCtx); } } result.Errors = new Exception[0]; } catch (Exception ex) { AggregateException aggEx = ex as AggregateException; if (aggEx == null) { aggEx = new AggregateException(new Exception[] { ex }); } result.Errors = CollectionHelper.AsArray(aggEx.Flatten().InnerExceptions); } return(result); }
public Module5DtoDomain(IHttpRequestContext requestContext) { _requestContext = requestContext; }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task<IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode = 200; string page = (context.Request.RawUrl ?? "").Split('?')[0].ToLower(); byte[] result; if (PageListen.ContainsKey(page)) { var func = PageListen[page]; result = func(context); return new ByteResponse(statusCode, "OK", result); } return new ByteResponse(404, "Not found", Encoding.UTF8.GetBytes("")); }
public DtoDomain(IHttpRequestContext httpRequestContext) { _httpRequestContext = httpRequestContext; }
public CommentService(CaffStoreDbContext context, IHttpRequestContext requestContext, IMapper mapper) { _context = context; _requestContext = requestContext; _mapper = mapper; }
private static byte[] OnService(IHttpRequestContext context) { return(new MyHttpHandler().ProcessRequest(context)); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="body"></param> /// <returns></returns> protected byte[] ProcessResponse(IHttpRequestContext context, ResponseBody body) { return ResponseFormater.Serialize(body); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="param"></param> /// <returns></returns> protected virtual bool CheckSign(IHttpRequestContext context, out string param) { param = null; string query; string sign; if ("POST".Equals(context.Request.HttpMethod)) { string postString; using (var read = new StreamReader(context.Request.InputStream)) { postString = read.ReadToEnd(); } var signIdx = postString.IndexOf("sign=", StringComparison.InvariantCultureIgnoreCase); if (signIdx == -1) return false; param = postString.Substring(0, signIdx - 1); sign = signIdx + 5 < postString.Length ? postString.Substring(signIdx + 5) : ""; } else { sign = context.Request.QueryString["sign"]; if (string.IsNullOrEmpty(sign)) return false; query = context.Request.Url.Query.Substring(1); var signIdx = query.IndexOf("sign", StringComparison.InvariantCultureIgnoreCase); if (signIdx == -1) return false; param = query.Substring(0, signIdx - 1); } var mysign = CryptoHelper.MD5_Encrypt(param + HandlerManager.SignKey, Encoding.UTF8); return String.Compare(sign, mysign, StringComparison.OrdinalIgnoreCase) == 0; }
public HttpOperationContext(WebOperationContext webOperationContext) { _requestContext = new HttpRequestContext(webOperationContext.IncomingRequest); _responseContext = new HttpResponseContext(webOperationContext.OutgoingResponse); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="body"></param> protected virtual void OnRequest(IHttpRequestContext context, ResponseBody body) { }
public HttpOperationContext(IHttpRequestContext requestContext, IHttpResponseContext responseContext) { _requestContext = requestContext; _responseContext = responseContext; }
public CaffStoreDbContext(DbContextOptions <CaffStoreDbContext> options, ITimeService timeService, IHttpRequestContext requestContext) : base(options) { _timeService = timeService; _requestContext = requestContext; }
/// <summary> /// /// </summary> /// <param name="state"></param> /// <returns></returns> public Task<IHttpResponseAction> Execute(IHttpRequestContext state) { return NullTask; }
public async Task Patch <T>(T model, string url, IHttpRequestContext context = null) { await Patch(url, model); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task<IHttpResponseAction> Execute(IHttpRequestContext context) { int statusCode; RequestPackage package; var actionDispatcher = GameEnvironment.Setting.ActionDispatcher; if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode)) { return new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0]); } GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request); session.ProxySid = package.ProxySid; } else { session = (string.IsNullOrEmpty(package.SessionId) ? GameSession.GetSessionByCookie(context.Request) : GameSession.Get(package.SessionId)) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request); } package.Bind(session); ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session); if (package.IsUrlParam) { httpGet["UserHostAddress"] = session.RemoteAddress; httpGet["ssid"] = session.KeyCode.ToString("N"); httpGet["http"] = "1"; } var result = await System.Threading.Tasks.Task.Run<byte[]>(() => { try { return ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet); } catch (Exception ex) { TraceLog.WriteError("Excute mainclass error:{0}", ex); return new byte[0]; } }); string sessionId = session.SessionId; var response = new ByteResponse(statusCode, "OK", result); response.CookieHandle += ctx => { var cookie = ctx.Request.Cookies["sid"]; if (cookie == null) { cookie = new Cookie("sid", sessionId); cookie.Expires = DateTime.Now.AddMinutes(5); ctx.Response.SetCookie(cookie); } }; return response; }
public static HttpRequestBuilder BuildRequestFromContext(HttpRequestBuilder builder, IHttpRequestContext context) { if (context != null) { builder.AddTimeout(new System.TimeSpan(0, 0, 0, context.Timeout)); builder.AddHost(context.Host); builder.AddAcceptHeader(context.Accept); builder.AddUserAgent(context.UserAgent); builder.AddReferer(context.Referer); builder.AddHeaders(context.Headers); builder.AddCookies(context.Cookies); } return(builder); }
public async Task <T> Get <T>(string url, IHttpRequestContext context = null) { var response = await Get(url, context); return(response.ContentAsType <T>()); }
/// <summary> /// Main logic. /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task<IHttpResponseAction> Execute(IHttpRequestContext context) { var req = context.Request; // Handle GET requests only: if (req.HttpMethod != "GET") return new JsonRootResponse(statusCode: 405, statusDescription: "HTTP Method Not Allowed", message: "HTTP Method Not Allowed"); var rsp = await ProcessRequest(context); if (rsp == null) return null; // Not a JSON response? Return it: var root = rsp as JsonRootResponse; if (root == null) return rsp; // Check request header X-Exclude: string xexclude = req.Headers["X-Exclude"]; if (xexclude == null) return rsp; // Comma-delimited list of response items to exclude: string[] excluded = xexclude.Split(',', ' '); bool includeLinks = true, includeMeta = true; if (excluded.Contains("links", StringComparer.OrdinalIgnoreCase)) includeLinks = false; if (excluded.Contains("meta", StringComparer.OrdinalIgnoreCase)) includeMeta = false; // If nothing to exclude, return the original response: if (includeLinks & includeMeta) return rsp; // Filter out 'links' and/or 'meta': return new JsonRootResponse( statusCode: root.statusCode, statusDescription: root.statusDescription, message: root.message, links: includeLinks ? root.links : null, meta: includeMeta ? root.meta : null, errors: root.errors, results: root.results ); }
/// <summary> /// /// </summary> /// <param name="state"></param> /// <returns></returns> public Task <IHttpResponseAction> Execute(IHttpRequestContext state) { return(NullTask); }
async Task<IHttpResponseAction> ProcessRequest(IHttpRequestContext context) { var req = context.Request; // Capture the current service configuration values only once per connection in case they update during: var main = this.services; var services = main.Value.Services.Services; // Not getting any further than this with severe errors: if (main.Value.Services.Errors.Count > 0) { return new JsonRootResponse( statusCode: 500, message: "Severe errors encountered", errors: main.Value.Services.Errors.ToArray() ); } // Split the path into component parts: string[] path; string absPath = req.Url.AbsolutePath; if (absPath == "/") path = new string[0]; else path = absPath.Substring(1).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (path.Length == 0) { // Our default response when no action is given: return new JsonRootResponse( links: new RestfulLink[] { RestfulLink.Create("config", "/config"), RestfulLink.Create("meta", "/meta"), RestfulLink.Create("errors", "/errors"), RestfulLink.Create("debug", "/debug") }, meta: new { configHash = main.HashHexString } ); } string actionName = path[0]; // Requests are always of one of these forms: // * /{action} // * /{action}/{service} // * /{action}/{service}/{method} try { if (path.Length == 1) { if (actionName == "data") { return new RedirectResponse("/meta"); } else if (actionName == "meta") { return metaAll(main); } else if (actionName == "debug") { return debugAll(main); } else if (actionName == "config") { return configAll(main); } else if (actionName == "errors") { return errorsAll(main); } else { return new JsonRootResponse( statusCode: 400, statusDescription: "Unknown action", message: "Unknown action '{0}'".F(actionName), meta: new { configHash = main.HashHexString, }, errors: new[] { new { actionName } } ); } } // Look up the service name: string serviceName = path[1]; Service service; if (!main.Value.Services.Services.TryGetValue(serviceName, out service)) return new JsonRootResponse( statusCode: 400, statusDescription: "Unknown service name", message: "Unknown service name '{0}'".F(serviceName), meta: new { configHash = main.HashHexString }, errors: new[] { new { serviceName } } ); if (path.Length == 2) { if (actionName == "data") { return new RedirectResponse("/meta/{0}".F(serviceName)); } else if (actionName == "meta") { return metaService(main, service); } else if (actionName == "debug") { return debugService(main, service); } else if (actionName == "errors") { // Report errors encountered while building a specific service descriptor. return errorsService(main, service); } else { return new JsonRootResponse( statusCode: 400, statusDescription: "Unknown request type", message: "Unknown request type '{0}'".F(actionName), meta: new { configHash = main.HashHexString }, errors: new[] { new { actionName } } ); } } if (path.Length > 3) { return new JsonRootResponse( statusCode: 400, statusDescription: "Too many path components supplied", message: "Too many path components supplied", meta: new { configHash = main.HashHexString } ); } // Find method: string methodName = path[2]; Method method; if (!service.Methods.TryGetValue(methodName, out method)) return new JsonRootResponse( statusCode: 400, statusDescription: "Unknown method name", message: "Unknown method name '{0}'".F(methodName), meta: new { configHash = main.HashHexString }, errors: new[] { new { methodName } } ); if (actionName == "data") { // Await execution of the method and return the results: var result = await dataMethod(main, method, req.QueryString); return result; } else if (actionName == "meta") { return metaMethod(main, service, method); } else if (actionName == "debug") { return debugMethod(main, service, method); } else if (actionName == "errors") { // Report errors encountered while building a specific method: return errorsMethod(main, service, method); } else { return new JsonRootResponse( statusCode: 400, statusDescription: "Unknown request type", message: "Unknown request type '{0}'".F(actionName), meta: new { configHash = main.HashHexString }, errors: new[] { new { actionName } } ); } } catch (Exception ex) { return getErrorResponse(ex); } }