public void Configure(IApplicationBuilder app) { //We are building a url template from scratch, segment by segemtn, oldskool var segment = new TemplateSegment(); segment.Parts.Add(TemplatePart.CreateLiteral("page")); var segment2 = new TemplateSegment(); segment2.Parts.Add( TemplatePart.CreateParameter("title", isCatchAll: true, isOptional: true, defaultValue: null, inlineConstraints: new InlineConstraint[] {}) ); var segments = new TemplateSegment [] { segment, segment2 }; var template = new RouteTemplate("page", segments.ToList()); var templateMatcher = new TemplateMatcher(template, new RouteValueDictionary()); app.Use(async(context, next) => { await context.Response.WriteAsync("We are using two segments, one with Literal Template Part ('page') and the other with Parameter Template Part ('title')"); await context.Response.WriteAsync("\n\n"); await next.Invoke(); }); app.Use(async(context, next) => { var path1 = "/page/what"; 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 'title' is {routeData["title"]} \n"); await next.Invoke(); }); app.Use(async(context, next) => { var path1 = "/page/the/old/man/and/the/sea"; 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 'title' is {routeData["title"]} \n"); await next.Invoke(); }); app.Run(async context => { await context.Response.WriteAsync(""); }); }
public void Configure(IApplicationBuilder app) { //We are building a url template from scratch, segment by segemtn, oldskool var segment = new TemplateSegment(); segment.Parts.Add(TemplatePart.CreateLiteral("page")); var segment2 = new TemplateSegment(); segment2.Parts.Add(TemplatePart.CreateParameter("id", isCatchAll: false, isOptional: false, defaultValue: null, inlineConstraints: new InlineConstraint[] { new InlineConstraint("int") })); var segments = new TemplateSegment[] { segment, segment2 }; var template = new RouteTemplate("page", segments.ToList()); var templateMatcher = new TemplateMatcher(template, new RouteValueDictionary()); app.Use(async(context, next) => { await context.Response.WriteAsync("We are using one segment with two parts, one Literal Template Part ('page') and the other with Parameter Template Part ('id')."); await context.Response.WriteAsync("It is the equivalent of /page/{id:int}"); await context.Response.WriteAsync("\n\n"); await next.Invoke(); }); app.Use(async(context, next) => { var path1 = "/page/10"; 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/a"; 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} - as you can see TemplateMatcher does not give a damn about InlineConstraint. It is by design. \n"); }); }
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(); } } }
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"); }); }
/// <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 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 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); }
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()); var values = new RouteValueDictionary(); // Act var match = matcher.TryMatch(new PathString(path), values); // Assert if (expected == null) { Assert.False(match); } else { Assert.True(match); Assert.Equal(expected.Count, values.Count); foreach (string key in values.Keys) { Assert.Equal(expected[key], values[key]); } } }
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); }
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 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 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); } }
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); }
/// <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); }
private bool RequestingZipComponent(HttpRequest request, out string package, out string version, out string file) { package = null; version = null; file = null; if (request.Method != "GET") { return(false); } var routeValues = new RouteValueDictionary(); if (_requestMatcher.TryMatch(request.Path, routeValues) && routeValues.ContainsKey("package") && routeValues.ContainsKey("version") && routeValues.ContainsKey("file")) { package = routeValues["package"].ToString(); version = routeValues["version"].ToString(); file = routeValues["file"]?.ToString(); return(true); } return(false); }
public async Task Invoke(HttpContext context) { var routeValues = new RouteValueDictionary(); if (_isReportingEnabled && _templateMatcher.TryMatch(context.Request.Path, routeValues)) { var keys = _factory.GetMissingResources(); using (var ms = new MemoryStream()) { await _formatter.WriteAsync(ms, keys); ms.Position = 0; context.Response.StatusCode = 200; context.Response.ContentType = _formatter.ContentTypeProduced; await ms.CopyToAsync(context.Response.Body); } } else { // Call the next delegate/middleware in the pipeline await this._next(context); } }
private bool RequestingSwaggerUi(HttpRequest request) { if (request.Method != "GET") { return(false); } return(_requestMatcher.TryMatch(request.Path, new RouteValueDictionary())); }
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)); }
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); }
private MiddlerRuleMatch CheckMatch(IMiddlerOptions middlerOptions, MiddlerRule rule, MiddlerContext middlerContext) { var allowedHttpMethods = (rule.HttpMethods?.IgnoreNullOrWhiteSpace().Any() == true ? rule.HttpMethods.IgnoreNullOrWhiteSpace() : middlerOptions.DefaultHttpMethods).ToList(); if (allowedHttpMethods.Any() && !allowedHttpMethods.Contains(middlerContext.Request.HttpMethod, StringComparer.OrdinalIgnoreCase)) { return(null); } //var uri = new Uri(context.Request.GetEncodedUrl()); var allowedSchemes = (rule.Scheme?.IgnoreNullOrWhiteSpace().Any() == true ? rule.Scheme.IgnoreNullOrWhiteSpace() : middlerOptions.DefaultScheme).ToList(); if (allowedSchemes.Any() && !allowedSchemes.Any(scheme => Wildcard.Match(middlerContext.MiddlerRequestContext.Uri.Scheme, scheme))) { return(null); } if (!Wildcard.Match($"{middlerContext.MiddlerRequestContext.Uri.Host}:{middlerContext.MiddlerRequestContext.Uri.Port}", rule.Hostname ?? "*")) { return(null); } if (String.IsNullOrWhiteSpace(rule.Path)) { rule.Path = "{**path}"; } var parsedTemplate = TemplateParser.Parse(rule.Path); var defaults = parsedTemplate.Parameters.Where(p => p.DefaultValue != null) .Aggregate(new RouteValueDictionary(), (current, next) => { current.Add(next.Name, next.DefaultValue); return(current); }); var matcher = new TemplateMatcher(parsedTemplate, defaults); var rd = middlerContext.MiddlerRequestContext.GetRouteData(); var router = rd.Routers.FirstOrDefault() ?? new RouteCollection(); if (matcher.TryMatch(middlerContext.MiddlerRequestContext.Uri.AbsolutePath, rd.Values)) { var constraints = GetConstraints(middlerContext.RequestServices.GetRequiredService <IInlineConstraintResolver>(), parsedTemplate, null); if (MiddlerRouteConstraintMatcher.Match(constraints, rd.Values, router, RouteDirection.IncomingRequest, ConstraintLogger)) { middlerContext.SetRouteData(constraints); return(new MiddlerRuleMatch { MiddlerRule = rule, AccessMode = rule.AccessAllowed(middlerContext.Request) ?? middlerOptions.DefaultAccessMode }); } } return(null); }
public static bool IsMatchingRoute(this PathString path, string pattern) { var template = TemplateParser.Parse(pattern); var values = new RouteValueDictionary(); var matcher = new TemplateMatcher(template, values); return(matcher.TryMatch(path, values)); }
private const string ORG_ROUTETEMPLATE = "{org}/{controller}/{action}";///{area:exists} public static RouteValueDictionary Match(HttpContext context) { var template = TemplateParser.Parse(ORG_ROUTETEMPLATE); var matcher = new TemplateMatcher(template, GetDefaults(template)); var routeData = new RouteValueDictionary(); matcher.TryMatch(context.Request.Path.Value, routeData); return(routeData); }
public bool TryMatch(string routeTemplate, string requestPath, out RouteValueDictionary values) { var template = TemplateParser.Parse(routeTemplate); var matcher = new TemplateMatcher(template, this.GetDefaults(template)); values = new RouteValueDictionary(); return(matcher.TryMatch(requestPath, values)); }
private object CallControllerAction( string route, Controller[] controllers) { var actionDescriptors = _actionDescriptorCollectionProvider .ActionDescriptors .Items .Where(x => x ?.ActionConstraints ?.Any() == true) .OfType <ControllerActionDescriptor>(); foreach (var actionDescriptor in actionDescriptors) { var attributeRouteInformation = actionDescriptor.AttributeRouteInfo; if (attributeRouteInformation == null) { continue; } var template = TemplateParser.Parse(attributeRouteInformation.Template); var templateMatcher = new TemplateMatcher( template, GetRouteValueDefaults(template)); var values = new RouteValueDictionary(); if (!templateMatcher.TryMatch(route, values)) { continue; } var controller = controllers.SingleOrDefault(x => x.GetType() == actionDescriptor.ControllerTypeInfo); if (controller == null) { continue; } var method = actionDescriptor.MethodInfo; var parameters = method .GetParameters() .Select(x => { var value = values .Single(y => y.Key == x.Name) .Value; return(Convert.ChangeType(value, x.ParameterType)); }) .Cast <object>() .ToArray(); return(method.Invoke( controller, parameters)); } throw new InvalidOperationException("No controller to serve the route \"" + route + "\" was found."); }
private bool IsMatch(string template, string route) { var routeTemplate = TemplateParser.Parse(template); var matcher = new TemplateMatcher(routeTemplate, new RouteValueDictionary()); var values = new RouteValueDictionary(); return(matcher.TryMatch(route, values)); }
public static bool Match(string pattern, string queryString) { pattern = pattern.StartsWith('?') ? pattern.Substring(1) : pattern; queryString = "/" + (queryString.StartsWith('?') ? queryString.Substring(1) : queryString); var patternTemplate = TemplateParser.Parse(pattern); var patternMatcher = new TemplateMatcher(patternTemplate, null); var values = new RouteValueDictionary(); return(patternMatcher.TryMatch(queryString, values)); }
public static RouteValueDictionary MatchRoute(this string routeTemplate, string requestPath) { var templateWithSlash = routeTemplate.EnsureStartWithSlash(); var requestPathWithSlash = requestPath.EnsureStartWithSlash(); var template = TemplateParser.Parse(templateWithSlash); var matcher = new TemplateMatcher(template, GetDefaults(template)); var values = new RouteValueDictionary(); return(matcher.TryMatch(requestPathWithSlash, values) ? values : null); }
public async Task RouteAsync(RouteContext context) { EnsureLoggers(context.HttpContext); using (_logger.BeginScope("DomainTemplateRoute.RouteAsync")) { var requestHost = context.HttpContext.Request.Host.Value; if (IgnorePort && requestHost.Contains(":")) { requestHost = requestHost.Substring(0, requestHost.IndexOf(":")); } Console.WriteLine($"Subdomain name: {requestHost}"); // var routeValues = new RouteValueDictionary(); // var routeData = context.HttpContext.GetRouteData(); // var values = _matcher.Match(requestHost); var values = _matcher.TryMatch(context.HttpContext.Request.Path, new RouteValueDictionary(context.RouteData)); //if (values == null) if (!values) { if (_logger.IsEnabled(LogLevel.Trace)) { _logger.LogTrace("DomainTemplateRoute " + Name + " - Host \"" + context.HttpContext.Request.Host + "\" did not match."); } // If we got back a null value set, that means the URI did not match return; } var oldRouteData = context.RouteData; var newRouteData = new RouteData(oldRouteData); MergeValues(newRouteData.DataTokens, DataTokens); newRouteData.Routers.Add(_target); //MergeValues(newRouteData.Values, values.ToImmutableDictionary()); MergeValues(newRouteData.Values, new RouteValueDictionary(context.RouteData).ToImmutableDictionary()); try { context.RouteData = newRouteData; // delegate further processing to inner route await _innerRoute.RouteAsync(context); } finally { // Restore the original values to prevent polluting the route data. // if (!context.IsHandled) // { // context.RouteData = oldRouteData; // } } } }
bool matchRequesting(HttpRequest request) { if ("GET".Equals(request.HttpMethod, StringComparison.OrdinalIgnoreCase)) { var routeValues = new RouteValueDictionary(); var templateMatcher = new TemplateMatcher(TemplateParser.Parse(options.InitJsonPath), routeValues); return(templateMatcher.TryMatch(request.Path, new RouteValueDictionary())); } return(false); }
private bool RequestingFromPath(HttpRequest request) { if (request.Method != "GET") { return(false); } var routeValues = new RouteValueDictionary(); return(_requestMatcher.TryMatch(request.Path, routeValues)); //return (routeValues != null); }