/// <summary> /// Creates a new instance of the SendFileMiddleware. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="options">The configuration for this middleware.</param> public DirectoryBrowserMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, DirectoryBrowserOptions options) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (hostingEnv == null) { throw new ArgumentNullException(nameof(hostingEnv)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (options.Formatter == null) { throw new ArgumentException(Resources.Args_NoFormatter); } options.ResolveFileProvider(hostingEnv); _next = next; _options = options; _matchUrl = options.RequestPath; }
/// <summary> /// If the request path starts with the given pathMatch, execute the app configured via configuration parameter instead of /// continuing to the next component in the pipeline. /// </summary> /// <param name="app"></param> /// <param name="pathMatch">The path to match</param> /// <param name="configuration">The branch to take for positive path matches</param> /// <returns></returns> public static IAppBuilder Map(this IAppBuilder app, PathString pathMatch, Action<IAppBuilder> configuration) { if (app == null) { throw new ArgumentNullException("app"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal)) { throw new ArgumentException(Resources.Exception_PathMustNotEndWithSlash, "pathMatch"); } // put middleware in pipeline before creating branch var options = new MapOptions { PathMatch = pathMatch }; IAppBuilder result = app.Use<MapMiddleware>(options); // create branch and assign to options IAppBuilder branch = app.New(); configuration(branch); options.Branch = (AppFunc)branch.Build(typeof(AppFunc)); return result; }
public SteamAuthenticationOptions() { ProviderDiscoveryUri = "http://steamcommunity.com/openid/"; Caption = "Steam"; AuthenticationType = "Steam"; CallbackPath = new PathString("/signin-openidsteam"); }
public static async Task<SecurityCollection> GetSecuritiesAsync(this IMarketsFeature feature, string value) { var path = new PathString("/v1/markets/search").Add(new { q = value }); return await feature.Client.GetAsync<SecurityCollection>(path); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the application for OAuth based flow PublicClientId = "MxRblSync.Api"; OAuthAuthorizationOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Authenticate"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), Provider = new ApiAuthorizationProvider( _loginSessionRepository, _authKeyRepository, _userRepository, _hashingService, PublicClientId), #if DEBUG AllowInsecureHttp = true #else AllowInsecureHttp = false #endif }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthAuthorizationServer(OAuthAuthorizationOptions); OAuthAuthenticationOptions = new OAuthBearerAuthenticationOptions { Provider = new ApiAuthenticationProvider(_authKeyRepository) }; app.UseOAuthBearerAuthentication(OAuthAuthenticationOptions); }
/// <summary> /// Creates a new instance of the StaticFileMiddleware. /// </summary> /// <param name="next">The next middleware in the pipeline.</param> /// <param name="options">The configuration options.</param> /// <param name="loggerFactory">An <see cref="ILoggerFactory"/> instance used to create loggers.</param> public StaticFileMiddleware(RequestDelegate next, IHostingEnvironment hostingEnv, StaticFileOptions options, ILoggerFactory loggerFactory) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (hostingEnv == null) { throw new ArgumentNullException(nameof(hostingEnv)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (options.ContentTypeProvider == null) { throw new ArgumentException(Resources.Args_NoContentTypeProvider); } options.ResolveFileProvider(hostingEnv); _next = next; _options = options; _matchUrl = options.RequestPath; _logger = loggerFactory.CreateLogger<StaticFileMiddleware>(); }
public WSO2AuthenticationOptions() : base(Constants.DefaultAuthenticationType) { Caption = Constants.DefaultAuthenticationType; CallbackPath = new PathString("/signin-wso2"); AuthenticationMode = AuthenticationMode.Passive; BackchannelTimeout = TimeSpan.FromSeconds(60); }
/// <summary> /// Combines the given URI components into a string that is properly encoded for use in HTTP headers. /// Note that unicode in the HostString will be encoded as punycode. /// </summary> /// <param name="scheme">http, https, etc.</param> /// <param name="host">The host portion of the uri normally included in the Host header. This may include the port.</param> /// <param name="pathBase">The first portion of the request path associated with application root.</param> /// <param name="path">The portion of the request path that identifies the requested resource.</param> /// <param name="query">The query, if any.</param> /// <param name="fragment">The fragment, if any.</param> /// <returns></returns> public static string BuildAbsolute( string scheme, HostString host, PathString pathBase = new PathString(), PathString path = new PathString(), QueryString query = new QueryString(), FragmentString fragment = new FragmentString()) { var combinedPath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/"; var encodedHost = host.ToString(); var encodedQuery = query.ToString(); var encodedFragment = fragment.ToString(); // PERF: Calculate string length to allocate correct buffer size for StringBuilder. var length = scheme.Length + SchemeDelimiter.Length + encodedHost.Length + combinedPath.Length + encodedQuery.Length + encodedFragment.Length; return new StringBuilder(length) .Append(scheme) .Append(SchemeDelimiter) .Append(encodedHost) .Append(combinedPath) .Append(encodedQuery) .Append(encodedFragment) .ToString(); }
public void RegisterAsset(string name, string contents) { var extension = Path.GetExtension(name); var baseName = Regex.Replace(name, $"{extension}$", string.Empty); if (_options.Fingerprint) { var hash = GetHashString(contents); name = $"{baseName}-{hash}{extension}".ToLower(); } var asset = new Asset { SimpleName = $"{baseName}{extension}".ToLower(), Path = $"{_options.ServePath}/{name.ToLower()}", Contents = contents }; var pathString = new PathString(asset.Path); var existingAsset = _assetLookup.Values.FirstOrDefault(a => a.SimpleName == asset.SimpleName); if (!string.IsNullOrEmpty(existingAsset?.Path)) { _assetLookup.Remove(new PathString(existingAsset.Path)); } _assetLookup.Add(pathString, asset); }
public KentorAuthServicesAuthenticationOptions() : base(Constants.DefaultAuthenticationType) { AuthenticationMode = AuthenticationMode.Passive; Description.Caption = Constants.DefaultCaption; MetadataPath = new PathString(Constants.DefaultMetadataPath); }
public static async Task<string> GetAsync(this IAccountsFeature feature) { //var path = new PathString("/v1/user/profile"); var path = new PathString("/v1/accounts"); var result = await feature.Client.GetAsync(path); return await result.Content.ReadAsStringAsync(); }
public WinAuthenticationOptions() : base(Constants.DefaultAuthenticationType) { Description.Caption = Constants.DefaultAuthenticationType; CallbackPath = new PathString("/windowsAuth"); AuthenticationMode = AuthenticationMode.Active; }
public OAuthCodeAuthenticationOptions(string authenticationType) : base(authenticationType) { AuthenticationMode = AuthenticationMode.Active; CallbackPath = new PathString("/signin"); BackchannelTimeout = TimeSpan.FromMinutes(1); }
public TestRunner Test(Func<HttpContext, Func<Task>, Task> test) { var path = new PathString("/test"); actions[path] = test; return this; }
public TestRunner Setup(Func<HttpContext, Func<Task>, Task> setup) { var path = new PathString("/setup"); actions[path] = setup; return this; }
public static async Task<Expirations> GetOptionsExpirationsAsync(this IMarketsFeature feature, string symbol) { var path = new PathString("/v1/markets/options/expirations").Add(new { symbol = symbol }); return await feature.Client.GetAsync<Expirations>(path); }
public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl) { _context = context; _options = options; _matchUrl = matchUrl; _request = context.Request; _response = context.Response; _method = null; _isGet = false; _isHead = false; _subPath = PathString.Empty; _contentType = null; _fileInfo = null; _length = 0; _lastModified = new DateTime(); _etag = null; _etagQuoted = null; _lastModifiedString = null; _ifMatchState = PreconditionState.Unspecified; _ifNoneMatchState = PreconditionState.Unspecified; _ifModifiedSinceState = PreconditionState.Unspecified; _ifUnmodifiedSinceState = PreconditionState.Unspecified; _ranges = null; }
public LowCalorieAuthenticationServerOptions() : base("LowCalorieAuthentication") { this.AuthenticationMode = AuthenticationMode.Passive; TokenEndpointPath = new PathString("/token2"); GernerateLocalToken = false; }
public void GetVirtualPath_ReturnsDataTokens(RouteValueDictionary dataTokens, string routerName) { // Arrange var virtualPath = new PathString("/TestVirtualPath"); var pathContextValues = new RouteValueDictionary { { "controller", virtualPath } }; var pathContext = CreateVirtualPathContext( pathContextValues, GetRouteOptions(), routerName); var route = CreateTemplateRoute("{controller}", routerName, dataTokens); var routeCollection = new RouteCollection(); routeCollection.Add(route); var expectedDataTokens = dataTokens ?? new RouteValueDictionary(); // Act var pathData = routeCollection.GetVirtualPath(pathContext); // Assert Assert.NotNull(pathData); Assert.Same(route, pathData.Router); Assert.Equal(virtualPath, pathData.VirtualPath); Assert.Equal(expectedDataTokens.Count, pathData.DataTokens.Count); foreach (var dataToken in expectedDataTokens) { Assert.True(pathData.DataTokens.ContainsKey(dataToken.Key)); Assert.Equal(dataToken.Value, pathData.DataTokens[dataToken.Key]); } }
public RulesEndpoint( IRuleData ruleData) { _ruleData = ruleData; _draftRulesPath = new PathString("/rules"); _versionRulesPath = new PathString("/rules/{version}"); }
/// <summary> /// Adds a StatusCodePages middle-ware to the pipeline. Specifies that the response body should be generated by /// re-executing the request pipeline using an alternate path. This path may contain a '{0}' placeholder of the /// status code and a '{1}' placeholder of the status name. /// </summary> /// <param name="application">The application.</param> /// <param name="pathFormat">The string representing the path to the error page. This path may contain a '{0}' /// placeholder of the status code and a '{1}' placeholder of the status description.</param> /// <returns>The application.</returns> public static IApplicationBuilder UseStatusNamePagesWithReExecute( this IApplicationBuilder application, string pathFormat) { return application.UseStatusCodePages( async context => { var statusCode = context.HttpContext.Response.StatusCode; var status = (HttpStatusCode)context.HttpContext.Response.StatusCode; var newPath = new PathString(string.Format( CultureInfo.InvariantCulture, pathFormat, statusCode, status.ToString())); var originalPath = context.HttpContext.Request.Path; // Store the original paths so the application can check it. context.HttpContext.SetFeature<IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature() { OriginalPathBase = context.HttpContext.Request.PathBase.Value, OriginalPath = originalPath.Value, }); context.HttpContext.Request.Path = newPath; try { await context.Next(context.HttpContext); } finally { context.HttpContext.Request.Path = originalPath; context.HttpContext.SetFeature<IStatusCodeReExecuteFeature>(null); } }); }
//TODO: Include/exclude lists for claims? public LDAPAuthenticationOptions() : base(LDAPAuthenticationDefaults.AuthenticationType) { AntiForgeryCookieName = AntiForgeryConfig.CookieName; AntiForgeryFieldName = LDAPAuthenticationDefaults.AntiForgeryFieldName; AuthenticationMode = AuthenticationMode.Active; CallbackPath = new PathString("/signin-activedirectoryldap"); Caption = LDAPAuthenticationDefaults.Caption; ClaimTypes = new List<string>();//defaults? DomainKey = LDAPAuthenticationDefaults.DomainKey; //Domains = new List<DomainCredential>(); PasswordKey = LDAPAuthenticationDefaults.PasswordKey; ReturnUrlParameter = LDAPAuthenticationDefaults.ReturnUrlParameter; StateKey = LDAPAuthenticationDefaults.StateKey; UsernameKey = LDAPAuthenticationDefaults.UsernameKey; ValidateAntiForgeryToken = true; RequiredClaims = new ReadOnlyCollection<string>(new List<string> { AntiForgeryConfig.UniqueClaimTypeIdentifier, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType, ClaimTypesAD.DisplayName, ClaimTypesAD.Domain, ClaimTypesAD.Guid, System.Security.Claims.ClaimTypes.NameIdentifier, System.Security.Claims.ClaimTypes.PrimarySid }); }
public TestEndpoint( IRuleData ruleData) { _ruleData = ruleData; _draftVersionPath = new PathString("/test"); _versionPath = new PathString("/test/{version}"); }
public NestAuthenticationOptions() : base(Constants.DefaultAuthenticationType) { Description.Caption = Constants.DefaultAuthenticationType; CallbackPath = new PathString("/ExternalLoginCallback"); AuthenticationMode = AuthenticationMode.Passive; }
/// <summary> /// Branches the request pipeline based on matches of the given request path. If the request path starts with /// the given path, the branch is executed. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="pathMatch">The request path to match.</param> /// <param name="configuration">The branch to take for positive path matches.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal)) { throw new ArgumentException("The path must not end with a '/'", nameof(pathMatch)); } // create branch var branchBuilder = app.New(); configuration(branchBuilder); var branch = branchBuilder.Build(); var options = new MapOptions { Branch = branch, PathMatch = pathMatch, }; return app.Use(next => new MapMiddleware(next, options).Invoke); }
/// <summary> /// Enables static file serving for the given request path /// /// </summary> /// <param name="builder"/> /// <param name="defaultHtml">The default html to serve.</param> /// <returns/> public static IApplicationBuilder UseSpa(this IApplicationBuilder builder, string defaultHtml) { var options = new SpaOptions(); var pathString = new PathString(defaultHtml); options.DefaultHtml = pathString; return builder.UseSpa(options); }
public OpenIdConnectOptions(string authenticationScheme) { AuthenticationScheme = authenticationScheme; DisplayName = OpenIdConnectDefaults.Caption; CallbackPath = new PathString("/signin-oidc"); Events = new OpenIdConnectEvents(); }
/// <summary> /// Initializes a new instance of the <see cref="TwitterOptions"/> class. /// </summary> public TwitterOptions() { AuthenticationScheme = TwitterDefaults.AuthenticationScheme; DisplayName = AuthenticationScheme; CallbackPath = new PathString("/signin-twitter"); BackchannelTimeout = TimeSpan.FromSeconds(60); Events = new TwitterEvents(); }
/// <summary> /// Create an instance of the options initialized with the default values /// </summary> public MixedAuthOptions() : base("Windows") { Caption = MixedAuthConstants.DefaultAuthenticationType; CallbackPath = new PathString("/MixedAuth"); ClientId = "MixedAuth"; AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive; }
/// <summary> /// Combines the given URI components into a string that is properly encoded for use in HTTP headers. /// </summary> /// <param name="pathBase"></param> /// <param name="path"></param> /// <param name="query"></param> /// <param name="fragment"></param> /// <returns></returns> public static string Encode(PathString pathBase = new PathString(), PathString path = new PathString(), QueryString query = new QueryString(), FragmentString fragment = new FragmentString()) { string combinePath = (pathBase.HasValue || path.HasValue) ? (pathBase + path).ToString() : "/"; return combinePath + query + fragment; }
public static void SetupContainer(IAppBuilder app, IUnityContainer container, IPathMapper pathMapper, string virtualRoot, string routePrefix, string modulesPhysicalPath) { container.RegisterInstance(app); var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve <IModuleInitializerOptions>(); moduleInitializerOptions.VirtualRoot = virtualRoot; moduleInitializerOptions.RoutePrefix = routePrefix; //Initialize Platform dependencies var connectionString = ConfigurationHelper.GetConnectionStringValue("VirtoCommerce"); var hangfireOptions = new HangfireOptions { StartServer = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.Enabled", true), JobStorageType = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Jobs.StorageType", "Memory"), DatabaseConnectionString = connectionString, }; var hangfireLauncher = new HangfireLauncher(hangfireOptions); InitializePlatform(app, container, pathMapper, connectionString, hangfireLauncher, modulesPhysicalPath); var moduleManager = container.Resolve <IModuleManager>(); var moduleCatalog = container.Resolve <IModuleCatalog>(); var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator(); // Register URL rewriter for platform scripts var scriptsPhysicalPath = pathMapper.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator(); var scriptsRelativePath = MakeRelativePath(applicationBase, scriptsPhysicalPath); var platformUrlRewriterOptions = new UrlRewriterOptions(); platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), ""); app.Use <UrlRewriterOwinMiddleware>(platformUrlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath) }); // Register URL rewriter before modules initialization if (Directory.Exists(modulesPhysicalPath)) { var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath); var urlRewriterOptions = new UrlRewriterOptions(); foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>()) { var urlRewriteKey = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName); var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath); urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue); moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath); } app.Use <UrlRewriterOwinMiddleware>(urlRewriterOptions); app.UseStaticFiles(new StaticFileOptions { FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath) }); } container.RegisterInstance(GlobalConfiguration.Configuration); // Ensure all modules are loaded foreach (var module in moduleCatalog.Modules.OfType <ManifestModuleInfo>().Where(x => x.State == ModuleState.NotStarted)) { moduleManager.LoadModule(module.ModuleName); } SwaggerConfig.RegisterRoutes(container); // Post-initialize // Register MVC areas unless running in the Web Platform Installer mode if (IsApplication) { AreaRegistration.RegisterAllAreas(); } // Register other MVC resources GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Security OWIN configuration var authenticationOptions = new Core.Security.AuthenticationOptions { CookiesEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.Enabled", true), CookiesValidateInterval = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)), BearerTokensEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true), BearerTokensExpireTimeSpan = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)), HmacEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.Enabled", true), HmacSignatureValidityPeriod = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)), ApiKeysEnabled = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true), ApiKeysHttpHeaderName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"), ApiKeysQueryStringParameterName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"), }; OwinConfig.Configure(app, container, authenticationOptions); hangfireLauncher.ConfigureOwin(app, container); RecurringJob.AddOrUpdate <SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *"); var notificationManager = container.Resolve <INotificationManager>(); notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Registration notification", Description = "This notification is sent by email to a client when he finishes registration", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.RegistrationNotificationSubject, Body = PlatformNotificationResource.RegistrationNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Reset password notification", Description = "This notification is sent by email to a client upon reset password request", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.ResetPasswordNotificationSubject, Body = PlatformNotificationResource.ResetPasswordNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorEmailNotification(container.Resolve <IEmailNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); notificationManager.RegisterNotificationType(() => new TwoFactorSmsNotification(container.Resolve <ISmsNotificationSendingGateway>()) { DisplayName = "Two factor authentication", Description = "This notification contains a security token for two factor authentication", NotificationTemplate = new NotificationTemplate { Subject = PlatformNotificationResource.TwoFactorNotificationSubject, Body = PlatformNotificationResource.TwoFactorNotificationBody, Language = "en-US", } }); //Get initialized modules list sorted by dependency order var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules.OfType <ManifestModuleInfo>()) .Where(m => m.ModuleInstance != null && m.State == ModuleState.Initialized) .ToArray(); foreach (var module in postInitializeModules) { moduleManager.PostInitializeModule(module); } // SignalR var tempCounterManager = new TempPerformanceCounterManager(); GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager); var hubConfiguration = new HubConfiguration { EnableJavaScriptProxies = false }; app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration); // Initialize InstrumentationKey from EnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY") var appInsightKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(appInsightKey)) { TelemetryConfiguration.Active.InstrumentationKey = appInsightKey; } }
internal static bool PathEndsInSlash(PathString path) { return(path.Value.EndsWith("/", StringComparison.Ordinal)); }
internal static bool TryMatchPath(HttpContext context, PathString matchUrl, bool forDirectory, out PathString subpath) { var path = context.Request.Path; if (forDirectory && !PathEndsInSlash(path)) { path += new PathString("/"); } if (path.StartsWithSegments(matchUrl, out subpath)) { return(true); } return(false); }
public TriggerApiEndpoint(RequestDelegate next, PathString pathString) { _next = next; this.basePath = pathString; }
public static IApplicationBuilder MapWebSocket(this IApplicationBuilder app, PathString pathString) { return(app.Map(pathString, (_app) => _app.UseMiddleware <WebSocketMiddleware>())); }
public static IApplicationBuilder MapWebSocketHandler(this IApplicationBuilder app, PathString path, Func <WebSocket, IWebSocketConnection> factory) { return(app.Map(path, (_app) => _app.UseMiddleware <WebSocketMiddleware>(factory))); }
/// <summary> /// 使用<paramref name="pathString"/>配置路由中间件 /// </summary> /// <param name="app"></param> /// <param name="pathString"></param> /// <returns></returns> public static IApplicationBuilder UseRoutingScanning(this IApplicationBuilder app, PathString pathString) { app.Map(pathString, build => { var provider = build.ApplicationServices.GetService <IPathDescriptorProvider>(); build.Run(async context => { object body; if (context.Request.Method.Equals(HttpMethods.Get, StringComparison.OrdinalIgnoreCase)) { var paths = provider.GetDescriptors(); body = paths; context.Response.ContentType = "application/json"; } else { body = new ErrorOutput(SAE.CommonLibrary.StatusCodes.RequestInvalid); context.Response.StatusCode = 400; } await context.Response.WriteAsync(body.ToJsonString()); }); }); return(app); }
internal static bool LookupContentType(IContentTypeProvider contentTypeProvider, StaticFileOptions options, PathString subPath, out string contentType) { if (contentTypeProvider.TryGetContentType(subPath.Value, out contentType)) { return(true); } if (options.ServeUnknownFileTypes) { contentType = options.DefaultContentType; return(true); } return(false); }
internal static bool ValidatePath(HttpContext context, PathString matchUrl, out PathString subPath) => Helpers.TryMatchPath(context, matchUrl, forDirectory: false, out subPath);
public static IApplicationBuilder UseBranchWithServices <TServer>(this IApplicationBuilder app, PathString path, Action <IServiceCollection> servicesConfiguration, Action <IApplicationBuilder> appBuilderConfiguration) where TServer : class, IServer { var webHost = new WebHostBuilder(). ConfigureServices(s => s.AddSingleton <IServer, TServer>()). ConfigureServices(servicesConfiguration). UseStartup <EmptyStartup>(). Build(); var serviceProvider = webHost.Services; var serverFeatures = webHost.ServerFeatures; var appBuilderFactory = serviceProvider.GetRequiredService <IApplicationBuilderFactory>(); var branchBuilder = appBuilderFactory.CreateBuilder(serverFeatures); var factory = serviceProvider.GetRequiredService <IServiceScopeFactory>(); branchBuilder.Use(async(context, next) => { using (var scope = factory.CreateScope()) { context.RequestServices = scope.ServiceProvider; await next(); } }); appBuilderConfiguration(branchBuilder); var branchDelegate = branchBuilder.Build(); return(app.Map(path, builder => { builder.Use(async(context, next) => { await branchDelegate(context); }); })); }
private bool IsRouteWhitelisted(PathString routePath) { return(_whitelistedPathString.Any((ps) => routePath.StartsWithSegments(ps))); }
private bool IsHomePageRoute(PathString routePath) { return(routePath.ToString() == HomePageRoute); }
private bool IsFavIconRoute(PathString routePath) { return(routePath.ToString() == FaviconRoute); }
/// <summary> /// Create a new UnityPath using a PathString /// </summary> /// <param name="path"></param> public UnityPath(PathString path) { Path = path; }