public void Start()
        {
            DefaultHttpContextFactory = new DefaultHttpContextFactory(new DefaultServiceProviderFactory().CreateServiceProvider(SerCollection));
            if (PipeEntityes.Count > 1)
            {
                for (int i = 0; i < PipeEntityes.Count; i++)
                {
                    if (i != PipeEntityes.Count - 1)
                    {
                        PipeEntityes[i].Next = PipeEntityes[i + 1];
                    }
                    else
                    {
                        PipeEntityes[i].Next = new PipeEntity {
                            Action = (c, p) => { return(Task.CompletedTask); }
                        }
                    };
                }
            }

            Server = ServerBuilder.SetOwinApp(OwinApp).Build();
            Server.Start();

            Console.TreatControlCAsInput = false;
            while (true)
            {
                Console.ReadKey(true);
            }
        }

        ~CustomServer()
        {
            Server?.Dispose();
        }
    }
Esempio n. 2
0
        public static void UseSubAppModules(this IApplicationBuilder app, PathString modulePrefix = default)
        {
            app = app ?? throw new ArgumentNullException();

            //app.Map(modulePrefix, subapp =>
            //{
            //    subapp.UseRouting();
            //    subapp.UseEndpoints(b =>
            //    {
            //        b.MapGet("/", async http =>
            //         {
            //             await http.Response.WriteAsync(http.Request.PathBase);
            //         });
            //    });
            //});
            //return;

            var moduleManager = app.ApplicationServices.GetRequiredService <IModuleManager>();

            moduleManager.Initialize();
            var pipelineCacheManager = app.ApplicationServices.GetRequiredService <IPipelineCacheManager>();
            var modules = moduleManager.GetModules();

            app.MapWhen(http => http.Request.Path.StartsWithSegments(modulePrefix), subapp =>
            {
                foreach (var module in modules)
                {
                    subapp.Map(modulePrefix.Add("/" + module.ModuleName), subapp2 =>
                    {
                        var(requestDelegate, service, alc) = pipelineCacheManager.GetOrCache(module.ModuleName);
                        if (requestDelegate != null)
                        {
                            subapp2.UseRouting();
                            subapp2.UseEndpoints(builder => builder.MapGet("/appinfo", async(http) =>
                            {
                                if (http.Request.PathBase.StartsWithSegments(modulePrefix, out var prefixPath))
                                {
                                    var moduleName            = prefixPath.ToString().Remove(0, 1);
                                    http.Response.ContentType = "application/json;charset=utf-8";
                                    await http.Response.WriteAsync(JsonSerializer.Serialize(new
                                    {
                                        pathBase   = http.Request.PathBase.ToUriComponent(),
                                        moduleName = moduleName
                                    }));
                                }
                            }));
                            subapp2.Use(next => async http =>
                            {
                                var http2 = new DefaultHttpContextFactory(service).Create(http.Features);
                                using (alc.EnterContextualReflection())
                                {
                                    await requestDelegate(http2);
                                }
                            });
                        }
                    });
                }
        //public CustomServer SetFormOption(Action<FormOptions> setForm)
        //{
        //    SerCollection.AddSingleton<IOptions<FormOptions>>(services =>
        //    {
        //        return new OptionsManager<FormOptions>(new OptionsFactory<FormOptions>(new List<IConfigureOptions<FormOptions>> { new ConfigureOptions<FormOptions>(setForm) }, new List<IPostConfigureOptions<FormOptions>>() { }));
        //    });
        //    return this;
        //}

        public Task OwinApp(IDictionary <string, object> env)
        {
            var features = new FeatureCollection(new OwinFeatureCollection(env));
            var context  = DefaultHttpContextFactory.Create(features);

            if (PipeEntityes.Count != 0)
            {
                PipeEntityes[0].Action(context, PipeEntityes[0]?.Next);
            }
            return(Task.CompletedTask);
        }
    public void AllowsCreatingContextWithoutSettingAccessor()
    {
        // Arrange
        var services = new ServiceCollection()
                       .AddOptions()
                       .BuildServiceProvider();
        var contextFactory = new DefaultHttpContextFactory(services);

        // Act & Assert
        var context = contextFactory.Create(new FeatureCollection());

        contextFactory.Dispose(context);
    }
        public static HttpContext CreateHttpContext()
        {
            var services = new ServiceCollection()
                           .AddOptions()
                           .AddHttpContextAccessor()
                           .BuildServiceProvider();
            var contextFactory    = new DefaultHttpContextFactory(services);
            var featureCollection = new FeatureCollection();

            featureCollection.Set <IHttpResponseFeature>(new HttpResponseFeature());
            featureCollection.Set <IHttpRequestFeature>(new HttpRequestFeature());

            return(contextFactory.Create(featureCollection));
        }
Esempio n. 6
0
        public MemberSignInManager CreateSut()
        {
            // This all needs to be setup because internally aspnet resolves a bunch
            // of services from the HttpContext.RequestServices.
            var serviceProviderFactory = new DefaultServiceProviderFactory();
            var serviceCollection      = new ServiceCollection();

            serviceCollection
            .AddLogging()
            .AddAuthentication()
            .AddCookie(IdentityConstants.ApplicationScheme)
            .AddCookie(IdentityConstants.ExternalScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.ExternalScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorUserIdScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorUserIdScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(IdentityConstants.TwoFactorRememberMeScheme, o =>
            {
                o.Cookie.Name    = IdentityConstants.TwoFactorRememberMeScheme;
                o.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });
            IServiceProvider serviceProvider = serviceProviderFactory.CreateServiceProvider(serviceCollection);
            var httpContextFactory           = new DefaultHttpContextFactory(serviceProvider);
            IFeatureCollection features      = new DefaultHttpContext().Features;

            features.Set <IHttpConnectionFeature>(new HttpConnectionFeature
            {
                LocalIpAddress = IPAddress.Parse("127.0.0.1")
            });
            HttpContext httpContext = httpContextFactory.Create(features);

            _mockLogger = new Mock <ILogger <SignInManager <MemberIdentityUser> > >();
            return(new MemberSignInManager(
                       _memberManager.Object,
                       Mock.Of <IHttpContextAccessor>(x => x.HttpContext == httpContext),
                       CreateClaimsFactory(_memberManager.Object),
                       Mock.Of <IOptions <IdentityOptions> >(),
                       _mockLogger.Object,
                       Mock.Of <IAuthenticationSchemeProvider>(),
                       Mock.Of <IUserConfirmation <MemberIdentityUser> >(),
                       Mock.Of <IMemberExternalLoginProviders>(),
                       Mock.Of <IEventAggregator>()
                       ));
        }
    public void CreateHttpContextSetsHttpContextAccessor()
    {
        // Arrange
        var services = new ServiceCollection()
                       .AddOptions()
                       .AddHttpContextAccessor()
                       .BuildServiceProvider();
        var accessor       = services.GetRequiredService <IHttpContextAccessor>();
        var contextFactory = new DefaultHttpContextFactory(services);

        // Act
        var context = contextFactory.Create(new FeatureCollection());

        // Assert
        Assert.Same(context, accessor.HttpContext);
    }
Esempio n. 8
0
 public HostingApplication(
     RequestDelegate application,
     ILogger logger,
     DiagnosticListener diagnosticSource,
     IHttpContextFactory httpContextFactory)
 {
     _application = application;
     _diagnostics = new HostingApplicationDiagnostics(logger, diagnosticSource);
     if (httpContextFactory is DefaultHttpContextFactory factory)
     {
         _defaultHttpContextFactory = factory;
     }
     else
     {
         _httpContextFactory = httpContextFactory;
     }
 }
    public void SetsDefaultPropertiesOnHttpContext()
    {
        // Arrange
        var services = new ServiceCollection()
                       .AddOptions()
                       .BuildServiceProvider();
        var contextFactory = new DefaultHttpContextFactory(services);

        // Act & Assert
        var context = contextFactory.Create(new FeatureCollection()) as DefaultHttpContext;

        Assert.NotNull(context);
        Assert.NotNull(context.FormOptions);
        Assert.NotNull(context.ServiceScopeFactory);

        Assert.Same(services.GetRequiredService <IServiceScopeFactory>(), context.ServiceScopeFactory);
    }
Esempio n. 10
0
    public void CreateHttpContextSetsActiveField()
    {
        // Arrange
        var services = new ServiceCollection()
                       .AddOptions()
                       .BuildServiceProvider();
        var contextFactory = new DefaultHttpContextFactory(services);

        // Act & Assert
        var context = contextFactory.Create(new FeatureCollection()) as DefaultHttpContext;

        Assert.True(context._active);

        context.Uninitialize();

        Assert.False(context._active);
    }
        public static HttpContext CreateHttpContext()
        {
            var services = new ServiceCollection()
                           .AddOptions()
                           .AddHttpContextAccessor()
                           .BuildServiceProvider();
            var contextFactory    = new DefaultHttpContextFactory(services);
            var featureCollection = new FeatureCollection();

            featureCollection.Set <IHttpResponseFeature>(new HttpResponseFeature());
            featureCollection.Set <IHttpRequestFeature>(new HttpRequestFeature());

            HttpContext httpContext = contextFactory.Create(featureCollection);

            httpContext.Response.Body = new MemoryStream();
            httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
            return(httpContext);
        }
Esempio n. 12
0
 public MockHttpContextFactory(IOptions <FormOptions> formOptions, IHttpContextAccessor httpContextAccessor,
                               MockClaimsPrincipalProvider mockClaimsPrincipalProvider, IServiceProvider serviceProvider)
 {
     _delegate = new DefaultHttpContextFactory(serviceProvider);
     _mockClaimsPrincipalProvider = mockClaimsPrincipalProvider;
 }
Esempio n. 13
0
        public static async Task <IHtmlContent> RenderComponentAsync(
            Type componentType,
            Action <IServiceCollection> configureServices,
            IDictionary <string, object> parameters = null,
            RenderMode renderMode = RenderMode.Static)
        {
            var diContainer = new ServiceCollection();

            diContainer.AddLogging();
            diContainer.AddRazorPages();
            configureServices(diContainer);
            diContainer.TryAddScoped(sp => new HttpClient {
                BaseAddress = new Uri("http://localhost:5000/")
            });

            using var serviceProvider = diContainer.BuildServiceProvider();
            using var scope           = serviceProvider.CreateScope();

            var featureCollection = new FeatureCollection();

            featureCollection.Set <IHttpRequestFeature>(new HttpRequestFeature
            {
                Protocol    = "HTTP/2",
                Scheme      = "http",
                Method      = "GET",
                PathBase    = "",
                Path        = "/",
                QueryString = "",
                RawTarget   = "/",
                Headers     = { { "Host", "localhost:5000" } }
            });
            featureCollection.Set <IHttpResponseFeature>(new HttpResponseFeature());

            var httpContextFactory = new DefaultHttpContextFactory(scope.ServiceProvider);
            var httpContext        = httpContextFactory.Create(featureCollection);

            var attributes = new TagHelperAttributeList();

            var tagHelperContext = new TagHelperContext(attributes, new Dictionary <object, object>(), Guid.NewGuid().ToString("N"));

            var tagHelperOutput = new TagHelperOutput(
                tagName: string.Empty,
                attributes,
                getChildContentAsync: (_, _) => Task.FromResult(new DefaultTagHelperContent() as TagHelperContent));

            var componentTagHelper = new ComponentTagHelper
            {
                ComponentType = componentType,
                RenderMode    = renderMode,
                Parameters    = parameters,
                ViewContext   = new ViewContext {
                    HttpContext = httpContext
                }
            };

            await componentTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);

            httpContextFactory.Dispose(httpContext);

            return(tagHelperOutput.Content);
        }
Esempio n. 14
0
 public TracingHttpContextFactory(IServiceProvider serviceProvider)
 {
     _defaultFactory = new DefaultHttpContextFactory(serviceProvider);
 }