bool MatchRequesting(HttpRequest request, out string query) { query = null; if ("GET".Equals(request.Method, StringComparison.OrdinalIgnoreCase)) { var routeValues = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(TemplateParser.Parse(routeTemplate), routeValues); if (templateMatcher.TryMatch(request.Path, routeValues)) { query = jsonqlOptions.FindQuery?.Invoke(request); if (query == null) { query = request.Query["query"]; } if (query == null) { query = request.Headers["query"]; } if (query == null) { using (var reader = new StreamReader(request.Body)) query = reader.ReadToEnd(); } return(true); } } return(false); }
public bool HandleRequest(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var values = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(_routeTemplate, values); var isMatch = templateMatcher.TryMatch(context.Request.Path, values); if (!isMatch) { return(false); } var httpRequestConverter = new HttpRequestConverter(_jsonSerializerService); var arguments = httpRequestConverter.WrapContext(context); try { var result = _handler(arguments) ?? new Dictionary <object, object>(); httpRequestConverter.UnwrapContext(result, context); return(true); } catch (Exception exception) { _logger.LogError(exception, "Error while intercepting HTTP request."); } return(false); }
public async Task GivenMultipleTemplates_WhenRetrievingTemplates_ThenReturnsTemplateWithMostMatchedFields() { Mock <IRequest> mockrequest = new Mock <IRequest>(); mockrequest.Setup(x => x.GetProperties()).Returns(new[] { "a", "b", "c" }); var templateOne = CreateTemplate(response: "{ \"a\":\"1\" }", properties: new [] { "a" }); var templateTwo = CreateTemplate(response: "{ \"a\": \"1\",\"b\": \"2\" }", properties: new[] { "a", "b" }); var templateThree = CreateTemplate(response: "{ \"a\": \"1\",\"b\": \"2\",\"c\": \"3\", \"d\": \"4\" }", properties: new[] { "a", "b", "c", "d" }); var expectedTemplate = CreateTemplate(response: "{ \"a\": \"1\",\"b\": \"2\",\"c\": \"3\" }", properties: new[] { "a", "b", "c" }); Mock <ITemplateStore <ITemplate> > mockTemplateStore = new Mock <ITemplateStore <ITemplate> >(); Mock <ITemplateContainer <ITemplate> > mockTemplateContainer = new Mock <ITemplateContainer <ITemplate> >(); mockTemplateContainer.Setup(x => x.Templates).Returns(new[] { templateOne, templateTwo, templateThree, expectedTemplate }.ToList()); mockTemplateStore.Setup(x => x.GetTemplateContainerAsync(It.IsAny <Uri>(), CancellationToken.None)) .ReturnsAsync(mockTemplateContainer.Object); TemplateMatcher <ITemplate> templateMatcher = new TemplateMatcher <ITemplate>(mockTemplateStore.Object); var actualTemplate = await templateMatcher.MatchAsync(new Uri("http://anything"), mockrequest.Object, CancellationToken.None); Assert.That(actualTemplate, Is.EqualTo(expectedTemplate)); }
public static TemplateMatcher GetTemplateMatcher(string routeTemplate) { var template = TemplateParser.Parse(routeTemplate); var matcher = new TemplateMatcher(template, GetDefaults(template)); return(matcher); }
public ReDocMiddleware(RequestDelegate next, string path, string swaggerPath, string title) { _next = next; _requestMatcher = new TemplateMatcher(TemplateParser.Parse(path), new RouteValueDictionary()); _swaggerPath = swaggerPath; _title = title; }
public bool paused = false; // This variable is set by the pause() method and unset by the resume() method - when true it disables frame monitoring temporarily. //renderableGesture = null; // Implementations that record a gestures for graphical rendering should store the data for the last detected gesture in this array. /** * The controller initialization function - this is called just after a new instance of the controller is created to parse the options array, * connect to the Leap Motion device (unless an existing Leap.Controller object was passed as a parameter), and register a frame listener with * the leap controller. * * @param options */ void Awake() { /* * The current DEFAULT recognition algorithm is geometric template matching - which is initialized here. */ this.templateMatcher = new GeometricalMatcher(); }
public void Configure(IApplicationBuilder app) { app.Use(async(context, next) => { var path1 = "/page/10"; RouteTemplate template = TemplateParser.Parse("page/{id}"); var templateMatcher = new TemplateMatcher(template, new RouteValueDictionary()); var routeData = new RouteValueDictionary();//This dictionary will be populated by the parameter template part (in this case "title") var isMatch1 = templateMatcher.TryMatch(path1, routeData); await context.Response.WriteAsync($"{path1} is match? {isMatch1} => route data value for 'id' is {routeData["id"]} \n"); await next.Invoke(); }); app.Use(async(context, next) => { var path = "/page/gone/a"; RouteTemplate template = TemplateParser.Parse("page/gone/{id}"); var templateMatcher = new TemplateMatcher(template, new RouteValueDictionary()); var routeData = new RouteValueDictionary();//This dictionary will be populated by the parameter template part (in this case "title") var isMatch1 = templateMatcher.TryMatch(path, routeData); await context.Response.WriteAsync($"{path} is match? {isMatch1} => route data value for 'id' is {routeData["id"]} \n"); }); }
public async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { await _next.Invoke(context); return; } var defatuls = new RouteValueDictionary(); var matcher = new TemplateMatcher(_routeTemplate, defatuls); var ret = matcher.TryMatch(new PathString(context.Request.Path.Value), defatuls); if (!ret) { await _next.Invoke(context); return; } var process = (WebSocketMiddleware)System.Activator.CreateInstance(this.GetType(), _next); process._defautls = defatuls; await process.ProcessMessage(context); }
public ApiHelpMiddleware(RequestDelegate next, ApiHelpUIOptions options) { _next = next; _options = options; _requestMatcher = new TemplateMatcher(TemplateParser.Parse(_options.IndexPath), new RouteValueDictionary()); _resourceAssembly = GetType().GetTypeInfo().Assembly; // set the index resource name. _templateResourceName = "Microsoft.AspNetCore.ApiHelp.UI."; switch (_options.UI) { case ApiHelpUI.Swagger: _templateResourceName += "Swagger.dist.index.html"; break; case ApiHelpUI.JsonH: _templateResourceName += "JsonH.index.html"; break; case ApiHelpUI.JsonEditor: _templateResourceName += "JsonEditor.index.html"; break; default: throw new ArgumentOutOfRangeException(nameof(options)); } }
public IDictionary <string, object> Match(string routeTemplate, string requestPath, IQueryCollection query = null) { // The TemplateParser can only parse the route part (path), and not the query string. // If the template provided by the user also has a query string, we separate that and match it manually. requestPath = requestPath.SliceTill("?"); var regex = new Regex(@"(.*)(\?[^{}]*$)"); var match = regex.Match(routeTemplate); if (match.Success) { var queryString = match.Groups[2].Value; routeTemplate = match.Groups[1].Value; var queryInTemplate = QueryHelpers.ParseQuery(queryString); if (query?.All(arg => queryInTemplate.ContainsKey(arg.Key.TrimStart('?')) && queryInTemplate[arg.Key.TrimStart('?')] == arg.Value) != true) { return(null); } } var template = TemplateParser.Parse(routeTemplate.SliceTill("?")); var matcher = new TemplateMatcher(template, this.GetDefaults(template)); var values = new RouteValueDictionary(); if (matcher.TryMatch(requestPath.StartsWith("/", StringComparison.OrdinalIgnoreCase) ? requestPath : $"/{requestPath}", values)) { return(this.EnsureParameterConstraints(template, values)); } else { return(null); } }
/// <summary> /// Get route values for current route /// </summary> /// <param name="context">Route context</param> /// <returns>Route values</returns> protected RouteValueDictionary GetRouteValues(RouteContext context) { var path = context.HttpContext.Request.Path.Value; if (this.SeoFriendlyUrlsForPathEnabled && !this.SeoFriendlyUrlsForLanguagesEnabled) { string lastpath = path.Split('/').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault(); path = $"/{lastpath}"; } //remove language code from the path if it's localized URL if (this.SeoFriendlyUrlsForLanguagesEnabled && path.IsLocalizedUrl(context.HttpContext.Request.PathBase, false, out Language language)) { path = path.RemoveLanguageSeoCodeFromUrl(context.HttpContext.Request.PathBase, false); } //parse route data var routeValues = new RouteValueDictionary(this.ParsedTemplate.Parameters .Where(parameter => parameter.DefaultValue != null) .ToDictionary(parameter => parameter.Name, parameter => parameter.DefaultValue)); var matcher = new TemplateMatcher(this.ParsedTemplate, routeValues); matcher.TryMatch(path, routeValues); return(routeValues); }
public static PythonDictionary match_template(string template, string path) { if (template == null) { throw new ArgumentNullException(nameof(template)); } if (path == null) { throw new ArgumentNullException(nameof(path)); } var routeTemplate = TemplateParser.Parse(template); var values = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(routeTemplate, values); var isMatch = templateMatcher.TryMatch(path, values); var resultValues = new PythonDictionary(); foreach (var value in values) { resultValues.Add(value.Key, Convert.ToString(value.Value, CultureInfo.InvariantCulture)); } return(new PythonDictionary { ["is_match"] = isMatch, ["values"] = resultValues }); }
public RouteValueDictionary Match(string routeTemplate, string requestPath, IQueryCollection query) { // The TemplateParser can only parse the route part, and not the query string. // If the template provided by the user also has a query string, we separate that and match it manually. var regex = new Regex(@"(.*)(\?[^{}]*$)"); var match = regex.Match(routeTemplate); if (match.Success) { var queryString = match.Groups[2].Value; routeTemplate = match.Groups[1].Value; var queryInTemplate = QueryHelpers.ParseQuery(queryString); if (!query.All(arg => queryInTemplate.ContainsKey(arg.Key.TrimStart('?')) && queryInTemplate[arg.Key.TrimStart('?')] == arg.Value)) { return(null); } } var template = TemplateParser.Parse(routeTemplate); var matcher = new TemplateMatcher(template, GetDefaults(template)); var values = new RouteValueDictionary(); return(matcher.TryMatch(requestPath, values) ? values : null); }
private static void RunTest( string template, string path, RouteValueDictionary defaults, IDictionary <string, object> expected) { // Arrange var matcher = new TemplateMatcher( TemplateParser.Parse(template), defaults ?? new RouteValueDictionary()); // Act var match = matcher.Match(new PathString(path)); // Assert if (expected == null) { Assert.Null(match); } else { Assert.NotNull(match); Assert.Equal(expected.Count, match.Values.Count); foreach (string key in match.Keys) { Assert.Equal(expected[key], match[key]); } } }
/// <summary> /// /// </summary> /// <param name="httpContext"></param> /// <param name="pathBase"></param> /// <returns></returns> public async Task InvokeAsync(HttpContext httpContext, string pathBase) { var request = httpContext.Request; if ("GET".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase)) { var routeValues = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(TemplateParser.Parse($"{pathBase}/schema.json"), routeValues); if (templateMatcher.TryMatch(request.Path, routeValues)) { var schema = JsonQLSchema.Generate(options.ResourceTypes); var content = JsonSerializer.Serialize(new { Title = options?.SchemaTitle, Description = options?.SchemaDescription, ServerUrl = options?.SchemaServerUrl, schema.ResourceInfos, schema.ResourceTypes, schema.ResourceMethods, }); var response = httpContext.Response; response.Clear(); response.StatusCode = 200; response.ContentType = "application/json"; response.Write(content); response.End(); } } await Task.FromResult(0); }
public async Task InvokeAsync(HttpContext httpContext, string routeTemplate) { var request = httpContext.Request; if ("GET".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase)) { var routeValues = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(TemplateParser.Parse(routeTemplate), routeValues); if (templateMatcher.TryMatch(request.Path, routeValues)) { var response = httpContext.Response; var jsonQLRequest = new JsonQLRequest(httpContext, jsonQLOptions); var authorized = jsonQLOptions.AuthorizeAsync == null || await jsonQLOptions.AuthorizeAsync(jsonQLRequest); if (authorized) { var result = await new JsonQLHandler(jsonQLOptions, jsonQLResourceTable).HandleAsync(jsonQLRequest); response.Clear(); response.StatusCode = 200; response.ContentType = "application/json"; response.Write(result); } else { response.StatusCode = 403; } response.End(); } } }
private void EnsureMatcher() { if (_matcher == null) { _matcher = new TemplateMatcher(ParsedTemplate, Defaults); } }
public ZipStreamerMiddleware(RequestDelegate next, ZipStreamerOptions options) { _next = next; _options = options; _requestMatcher = new TemplateMatcher(TemplateParser.Parse(_options.RouteTemplate), new RouteValueDictionary()); _mime = new FileExtensionContentTypeProvider(); }
public static bool TryGetDocument(this HttpContext context, AsyncApiOptions options, out string document) { document = null; #if NETSTANDARD2_0 var template = TemplateParser.Parse(options.Middleware.Route); var values = new RouteValueDictionary(); var matcher = new TemplateMatcher(template, values); if (!matcher.TryMatch(context.Request.Path, values)) { template = TemplateParser.Parse(options.Middleware.UiBaseRoute + "{*wildcard}"); matcher = new TemplateMatcher(template, values); matcher.TryMatch(context.Request.Path, values); } #else var values = context.Request.RouteValues; #endif if (!values.TryGetValue("document", out var value)) { return(false); } document = value.ToString(); return(true); }
public ReportMissingMiddleware(RequestDelegate next, IOptions <ReportOptions> options, IStringLocalizerFactory factory, IOutputFormatter formatter) { _next = next; var reportPath = options.Value.ReportPath; if (string.IsNullOrEmpty(reportPath)) { return; } _templateMatcher = new TemplateMatcher(TemplateParser.Parse($"{reportPath}/{{filename?}}"), new RouteValueDictionary()); if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } _formatter = formatter; if (factory is ReportMissingStringLocalizerFactory rmslf) { _factory = rmslf; } else { throw new InvalidOperationException($"{ nameof(ReportMissingMiddleware) } cannot be used without { nameof(ReportMissingStringLocalizerFactory) }"); } }
/// <summary> /// Add a route name and template for batching. /// </summary> /// <param name="routeName">The route name.</param> /// <param name="routeTemplate">The route template.</param> public void AddRoute(string routeName, string routeTemplate) { string newRouteTemplate = routeTemplate.StartsWith("/") ? routeTemplate.Substring(1) : routeTemplate; RouteTemplate parsedTemplate = TemplateParser.Parse(newRouteTemplate); TemplateMatcher matcher = new TemplateMatcher(parsedTemplate, new RouteValueDictionary()); templateMappings[matcher] = routeName; }
public SwaggerMiddleware( RequestDelegate next, SwaggerOptions options) { _next = next; _options = options ?? new SwaggerOptions(); _requestMatcher = new TemplateMatcher(TemplateParser.Parse(_options.RouteTemplate), new RouteValueDictionary()); }
public DocumentationMiddleware( RequestDelegate next, DocumentationOptions options) { _next = next; _options = options ?? new DocumentationOptions(); _requestMatcher = new TemplateMatcher(TemplateParser.Parse(options.RouteTemplate), new RouteValueDictionary()); }
public McmaApiRoute(string httpMethod, string path, Func <TRequest, McmaApiResponse, Task> handler) { HttpMethod = httpMethod; Path = path; Handler = handler; Template = new TemplateMatcher(TemplateParser.Parse(path), null); }
public RouteValueDictionary Match(string routeTemplate, string requestPath) { var template = TemplateParser.Parse(routeTemplate); var matcher = new TemplateMatcher(template, GetDefaults(template)); var values = new RouteValueDictionary(); return(matcher.TryMatch(requestPath, values) ? values : null); }
public Handler(TemplateMatcher routeTemplate, Func <IActionResult> actionSync, Func <Task <IActionResult> > actionAsync) { RouteTemplate = routeTemplate; ActionSync = actionSync; ActionAsync = actionAsync; }
public static bool MatchRoute(string routeTemplate, string requestPath) { RouteTemplate template = TemplateParser.Parse(routeTemplate); TemplateMatcher matcher = new TemplateMatcher(template, GetRouteDefaults(template)); RouteValueDictionary values = new RouteValueDictionary(); return(matcher.TryMatch(requestPath, values)); }
/// <summary> /// /// </summary> /// <param name="next"></param> /// <param name="options"></param> public ApiExplorerUIInitJsonMIddleware( RequestDelegate next, ApiExplorerUIOptions options) { this.next = next; this.requestMatcher = new TemplateMatcher(TemplateParser.Parse(options.InitJsonPath), new RouteValueDictionary()); this.options = options; }
/// <summary> /// Add a route name and template for openapi. /// </summary> /// <param name="prefixName">The route prefix name.</param> /// <param name="routeTemplate">The route template.</param> private void AddRoute(string prefixName, string routeTemplate) { string newRouteTemplate = routeTemplate.StartsWith("/", StringComparison.Ordinal) ? routeTemplate.Substring(1) : routeTemplate; RouteTemplate parsedTemplate = TemplateParser.Parse(newRouteTemplate); TemplateMatcher matcher = new TemplateMatcher(parsedTemplate, new RouteValueDictionary()); _templateMappings[matcher] = prefixName; }
public void ShouldReturnFalseIfQueriesParametersNotEquals() { //Arrange var templateUri = new Uri("http://localhost/api/products?x={xValue}&p1=1&p2=2"); var uri = new Uri("http://localhost/api/products?x={xValue}&p3=1&p4=2"); Assert.IsFalse(TemplateMatcher.Match(templateUri, uri)); }
private static void RunTest( string template, string path, IReadOnlyDictionary<string, object> defaults, IDictionary<string, object> expected) { // Arrange var matcher = new TemplateMatcher(TemplateParser.Parse(template), defaults); // Act var match = matcher.Match(path); // Assert if (expected == null) { Assert.Null(match); } else { Assert.NotNull(match); Assert.Equal(expected.Count, match.Values.Count); foreach (string key in match.Keys) { Assert.Equal(expected[key], match[key]); } } }