Esempio n. 1
0
 static void Main(string[] args)
 {
     var owinbuilder = new AppBuilder();
     OwinServerFactory.Initialize(owinbuilder.Properties);
     new SampleOwinApp.Startup().Configuration(owinbuilder);
     var builder = ServerBuilder.New()
         .SetPort(8888)
         .SetOwinApp(owinbuilder.Build())
         .SetOwinCapabilities((IDictionary<string, object>)owinbuilder.Properties[OwinKeys.ServerCapabilitiesKey])
         .SetExecutionContextFlow(ExecutionContextFlow.SuppressAlways);
     //builder
     //    .SetCertificate(new X509Certificate2("../../../sslcert/test.pfx", "nowin"))
     //    .RequireClientCertificate();
     var builder2 = ServerBuilder.New().SetPort(9999).SetOwinApp(owinbuilder.Build()).SetOwinCapabilities((IDictionary<string, object>)owinbuilder.Properties[OwinKeys.ServerCapabilitiesKey]);
     using (var server = builder.Build())
     using (var server2 = builder2.Build())
     {
         // Workaround for bug in Windows Server 2012 when ReadLine is called directly after AcceptAsync
         // By starting it in another thread and probably even later than calling readline it works
         Task.Run(() => server.Start());
         Task.Run(() => server2.Start());
         //using (new Timer(o =>
         //    {
         //        var s = (INowinServer)o;
         //        Console.WriteLine("Connections {0}/{1}", s.ConnectionCount, s.CurrentMaxConnectionCount);
         //    }, server, 2000, 2000))
         {
             Console.WriteLine("Listening on ports 8888 and 9999. Enter to exit.");
             Console.ReadLine();
         }
     }
 }
Esempio n. 2
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();
            app.UseStatusCodePages();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new {controller = "Home", action = "Index"});
            });

            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var builder = new AppBuilder();
                    var hubConfig = new HubConfiguration { EnableDetailedErrors = true };

                    builder.MapSignalR(hubConfig);

                    var appFunc = builder.Build(typeof(Func<IDictionary<string, object>, Task>)) as Func<IDictionary<string, object>, Task>;

                    return appFunc;
                });
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="IdentityServerBearerTokenValidationMiddleware" /> class.
        /// </summary>
        /// <param name="next">The next middleware.</param>
        /// <param name="options">The options.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public IdentityServerBearerTokenValidationMiddleware(AppFunc next, IdentityServerOAuthBearerAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            _next = next;
            _options = options;
            _logger = loggerFactory.Create(this.GetType().FullName);

            if (options.LocalValidationOptions != null)
            {
                var localBuilder = new AppBuilder();
                options.OnValidationAppBuilderCreated?.Invoke(localBuilder);
                localBuilder.UseOAuthBearerAuthentication(options.LocalValidationOptions);
                localBuilder.Run(ctx => next(ctx.Environment));
                _localValidationFunc = localBuilder.Build();
            }

            if (options.EndpointValidationOptions != null)
            {
                var endpointBuilder = new AppBuilder();
                options.OnValidationAppBuilderCreated?.Invoke(endpointBuilder);
                endpointBuilder.Properties["host.AppName"] = "foobar";

                endpointBuilder.UseOAuthBearerAuthentication(options.EndpointValidationOptions);
                endpointBuilder.Run(ctx => next(ctx.Environment));
                _endpointValidationFunc = endpointBuilder.Build();
            }
        }
        public void NonNullCorsRequestContext_CallsPolicyProvider()
        {
            IAppBuilder builder = new AppBuilder();
            bool wasCalled = false;
            builder.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = ctx =>
                    {
                        wasCalled = true;
                        return Task.FromResult<CorsPolicy>(null);
                    }
                }
            });

            builder.Run(context =>
            {
                context.Response.StatusCode = 200;
                return Task.FromResult(0);
            });

            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IOwinRequest request = CreateRequest("http://localhost/sample");
            request.Headers.Set(CorsConstants.Origin, "http://test");
            app(request.Environment).Wait();

            var response = new OwinResponse(request.Environment);
            Assert.Equal(true, wasCalled);
        }
Esempio n. 5
0
 /// <summary>
 /// 默认构造函数
 /// </summary>
 public Adapter()
 {
     var builder = new AppBuilder();
     var startup = new Startup();
     startup.Configuration(builder);
     _owinApp = builder.Build();
 }
Esempio n. 6
0
        static void Main(string[] args) {
            var appBuilder = new AppBuilder();
            Nowin.OwinServerFactory.Initialize(appBuilder.Properties);

            appBuilder.Use<ConsoleLogMiddleware>();

            appBuilder.Use<SimpleStaticFileMiddleWare>(System.IO.Path.Combine(Environment.CurrentDirectory, @"../../www"));

            var startup = new WebApi.Startup();
            startup.Configuration(appBuilder);

            var builder = new Nowin.ServerBuilder();
            const string ip = "127.0.0.1";
            const int port = 8888;
            builder.SetAddress(System.Net.IPAddress.Parse(ip)).SetPort(port)
                .SetOwinApp(appBuilder.Build())
                .SetOwinCapabilities((IDictionary<string, object>)appBuilder.Properties[Nowin.OwinKeys.ServerCapabilitiesKey]);

            using (var server = builder.Build()) {

                var serverRef = new WeakReference<Nowin.INowinServer>(server);

                Task.Run(() => {
                    Nowin.INowinServer nowinServer;
                    if (serverRef.TryGetTarget(out nowinServer)) {
                        nowinServer.Start();
                    }
                });

                var baseAddress = "http://" + ip + ":" + port + "/";
                Console.WriteLine("Nowin server listening {0}, press ENTER to exit.", baseAddress);

                Console.ReadLine();
            }
        }
Esempio n. 7
0
        public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            return app.UseOwin(setup => setup(next => {
                var builder = new AppBuilder();
                var lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
                
                var properties = new AppProperties(builder.Properties);
                properties.AppName = Guid.NewGuid().ToString();
                properties.OnAppDisposing = lifetime.ApplicationStopping;
                properties.DefaultApp = next;

                configuration(builder);

                return builder.Build<Func<IDictionary<string, object>, Task>>();
            }));
        }
Esempio n. 8
0
        public void Activate() {
            IAppBuilder appBuilder = new AppBuilder();
            appBuilder.Properties["host.AppName"] = _shellSettings.Name;

            var orderedMiddlewares = _owinMiddlewareProviders
                .SelectMany(p => p.GetOwinMiddlewares())
                .OrderBy(obj => obj.Priority, new FlatPositionComparer());

            foreach (var middleware in orderedMiddlewares) {
                middleware.Configure(appBuilder);
            }

            // register the Orchard middleware after all others
            appBuilder.UseOrchard();

            Func<IDictionary<string, object>, Task> pipeline = appBuilder.Build();

            var allRoutes = new List<RouteDescriptor>();
            allRoutes.AddRange(_routeProviders.SelectMany(provider => provider.GetRoutes()));
            allRoutes.AddRange(_httpRouteProviders.SelectMany(provider => provider.GetRoutes()));

            _routePublisher.Publish(allRoutes, pipeline);
            _modelBinderPublisher.Publish(_modelBinderProviders.SelectMany(provider => provider.GetModelBinders()));

            using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                using (var events = scope.Resolve<Owned<IOrchardShellEvents>>()) {
                    events.Value.Activated();
                }
            }

            _sweepGenerator.Activate();
        }
Esempio n. 9
0
 public void Start(Action<IAppBuilder> app, IPEndPoint endpoint)
 {
     AppBuilder appBuilder = new AppBuilder();
     app(appBuilder);
     var builder = ServerBuilder.New().SetEndPoint(endpoint).SetOwinApp(appBuilder.Build());
     //builder.SetCertificate(new X509Certificate2("certificate.pfx", "password"));
     webApp = builder.Start();
 }
 public object Configuration(IDictionary<string, object> properties)
 {
     var builder = new AppBuilder();
     builder.Run(context =>
             {
                 return context.Response.WriteAsync("SUCCESS");
             });
     return builder.Build<AppFunc>();
 }
 public object Configuration()
 {
     var builder = new AppBuilder();
     builder.Run(context =>
             {
                 return context.Response.WriteAsync("SUCCESS");
             });
     return builder.Build<AppFunc>();
 }
        public void PredicateTrue_BranchTaken()
        {
            IOwinContext context = new OwinContext();
            IAppBuilder builder = new AppBuilder();
            builder.MapWhen(TruePredicate, UseSuccess);
            var app = builder.Build<OwinMiddleware>();
            app.Invoke(context).Wait();

            Assert.Equal(200, context.Response.StatusCode);
        }
Esempio n. 13
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var appBuilder = new AppBuilder();
            appBuilder.UseNancy();
            var appFunc = appBuilder.Build<AppFunc>();

            var settings = new CefSettings();
            settings.RegisterOwinSchemeHandlerFactory("owin", appFunc);
            Cef.Initialize(settings);
        }
Esempio n. 14
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="TheaterMiddleware" /> class.
        /// </summary>
        /// <param name="theaterSettings">The histrio settings used to configure the middelware</param>
        internal TheaterMiddleware(TheaterSettings theaterSettings)
        {
            var controllerActivator = new TheaterControllerActivator(theaterSettings.Theater);

            MidFunc = next =>
            {
                var app = new AppBuilder();
                app.UseWebApi(GetWebApiConfiguration(controllerActivator));
                app.Run(ctx => next(ctx.Environment));
                return app.Build();
            };
        }
        public void PathMatchFunc_BranchTaken(string matchPath, string basePath, string requestPath)
        {
            IOwinContext context = CreateRequest(basePath, requestPath);
            IAppBuilder builder = new AppBuilder();
            builder.Map(matchPath, UseSuccess);
            var app = builder.Build<OwinMiddleware>();
            app.Invoke(context);

            Assert.Equal(200, context.Response.StatusCode);
            Assert.Equal(basePath, context.Request.PathBase.Value);
            Assert.Equal(requestPath, context.Request.Path.Value);
        }
        public async Task When_host_Nancy_via_IAppBuilder_should_read_X509Certificate2()
        {
            // Given
            var app = new AppBuilder();
            var bootstrapper = new ConfigurableBootstrapper(config => config.Module<TestModule>());

            var cert = @"-----BEGIN CERTIFICATE-----
                            MIICNTCCAZ4CCQC21XwOAYG32zANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJH
                            QjETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsT
                            BU5hbmN5MRswGQYDVQQDExJodHRwOi8vbmFuY3lmeC5vcmcwHhcNMTYwMjIyMTE1
                            NzQ3WhcNMTcwMjIxMTE1NzQ3WjBfMQswCQYDVQQGEwJHQjETMBEGA1UECBMKU29t
                            ZS1TdGF0ZTEOMAwGA1UEChMFTmFuY3kxDjAMBgNVBAsTBU5hbmN5MRswGQYDVQQD
                            ExJodHRwOi8vbmFuY3lmeC5vcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB
                            AMT4vOtIH9Fzad+8KCGjMPkkVpCtn+L5H97bnI3x+y3x5lY0WRsK8FyxVshY/7fv
                            TDeeVKUWanmbMkQjgFRYffA3ep3/AIguswYdANiNVHrx0L7DXNDcgsjRwaa6JVgQ
                            9iavlli0a80AF67FN1wfidlHCX53u3/fAjiSTwf7D+NBAgMBAAEwDQYJKoZIhvcN
                            AQEFBQADgYEAh12A4NntHHdVMGaw+2umXkWqCOyAPuNhyBGUHK5vGON+VG0HPFaf
                            8P8eMtdF4deBHkrfoWxRuGGn2tJzNpZLiEf23BAivEf36IqwfkVP7/zDwI+bjVXC
                            k64Un2uN8ALR/wLwfJzHfOLPtsca7ySWhlv8oZo2nk0vR34asQiGJDQ=
                            -----END CERTIFICATE-----
                            ";

            var embeddedCert = Encoding.UTF8.GetBytes(cert);

            app.Use(new Func<AppFunc, AppFunc>(next => (async env =>
            {
                env.Add("ssl.ClientCertificate", new X509Certificate(embeddedCert));
                await next.Invoke(env);
            })));

            app.UseNancy(opts =>
            {
                opts.Bootstrapper = bootstrapper;
                opts.EnableClientCertificates = true;
            });

            var appFunc = app.Build();

            var handler = new OwinHttpMessageHandler(appFunc);

            using (var httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri("http://localhost")
            })
            {
                // When
                var response = await httpClient.GetAsync(new Uri("http://localhost/ssl"));

                // Then
                Assert.Equal(System.Net.HttpStatusCode.OK, response.StatusCode);
            }
        }
Esempio n. 17
0
        public async Task ScriptFileCanBeExecutedByName()
        {
            var factory = new RoslynAppLoaderFactory();
            Func<string, IList<string>, Action<IAppBuilder>> loader = factory.Create((_, __) => null);
            Action<IAppBuilder> startup = loader.Invoke("Simple.csx", null);
            var builder = new AppBuilder();
            startup.Invoke(builder);
            var app = builder.Build<OwinMiddleware>();

            IOwinContext context = new OwinContext();
            await app.Invoke(context);
            context.Response.StatusCode.ShouldBe(24601);
        }
        public void Invoke_DoesNotAddHeaders_WhenOriginIsMissing()
        {
            IAppBuilder builder = new AppBuilder();
            builder.UseCors(CorsOptions.AllowAll);

            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IOwinRequest request = CreateRequest("http://localhost/sample");
            app(request.Environment).Wait();

            var response = new OwinResponse(request.Environment);
            Assert.Empty(response.Headers);
        }
        private static HttpClient CreateHttpClient(Func<TimeSpan> getMinDelay)
        {
            var app = new AppBuilder();
            app.MinResponseDelay(getMinDelay)
                .Use((context, _) =>
                {
                    context.Response.StatusCode = 200;
                    context.Response.ReasonPhrase = "OK";

                    return Task.FromResult(0);
                });
            return new HttpClient(new OwinHttpMessageHandler(app.Build()));
        }
        /// <summary>
        ///     Creats a command handling middlware.
        /// </summary>
        /// <param name="settings">Settings to configure the middleware.</param>
        /// <returns>An owin middleware function (MidFunc) that represents </returns>
        public static MidFunc HandleCommands(CommandHandlingSettings settings)
        {
            Ensure.That(settings, "settings").IsNotNull();

            return next =>
            {
                var webApiConfig = ConfigureWebApi(settings);
                var appBuilder = new AppBuilder();
                appBuilder
                    .UseWebApi(webApiConfig)
                    .Run(ctx => next(ctx.Environment));
                return appBuilder.Build();
            };
        }
 private static HttpClient CreateClient(int length, string reasonPhrase = null)
 {
     var app = new AppBuilder();
     app.MaxQueryStringLength(length)
         .Use((context, next) =>
         {
             context.Response.StatusCode = 200;
             context.Response.ReasonPhrase = "OK";
             return Task.FromResult(0);
         });
     return new HttpClient(new OwinHttpMessageHandler(app.Build()))
     {
         BaseAddress = new Uri("http://example.com")
     };
 }
 public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure, string owinHostAppName)
 {
     app.UseOwin(addToPipeline =>
     {
         addToPipeline(next =>
         {
             var builder = new AppBuilder();
             builder.Properties["builder.DefaultApp"] = next;
             builder.Properties["host.AppName"] = owinHostAppName;
             configure(builder);
             return builder.Build<AppFunc>();
         });
     });
     return app;
 }
Esempio n. 23
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public Adapter()
        {
            // 创建默认的AppBuilder
            var builder = new AppBuilder();

            // 实例化 Startup类
            // 这个类中必须有“Configuration”方法
            var startup = new Startup();

            // 调用Configuration方法,把自己的处理函数注册到处理流程中
            startup.Configuration(builder);

            // 生成OWIN“入口”函数
            _owinApp = builder.Build();
        }
        public void FoundDirectoryWithDefaultFile_PathModified(string baseUrl, string baseDir, string requestUrl)
        {
            IAppBuilder builder = new AppBuilder();
            builder.UseDefaultFiles(new DefaultFilesOptions()
            {
                RequestPath = new PathString(baseUrl),
                FileSystem = new PhysicalFileSystem(baseDir)
            });
            var app = (OwinMiddleware)builder.Build(typeof(OwinMiddleware));

            IOwinContext context = CreateEmptyRequest(requestUrl);
            app.Invoke(context).Wait();

            Assert.Equal(404, context.Response.StatusCode); // Passed through
            Assert.Equal(requestUrl + "default.html", context.Request.Path.Value); // Should be modified
        }
        public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configure)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    configure(appBuilder);

                    return appBuilder.Build<AppFunc>();
                });
            });
            return app;
        }
        public void SetUp()
        {
            Builder = new RequestBuilder();

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            var appBuilder = new AppBuilder();
            AddCompressionMiddleware(appBuilder);
            appBuilder.UseWebApi(config);

            HttpClient = new HttpClient(new OwinHttpMessageHandler(appBuilder.Build()))
            {
                BaseAddress = new Uri("http://localhost")
            };

        }
        /// <summary>
        /// Provides a Katana/ASP.NET Core bridge allowing to register middleware designed for OWIN/Katana.
        /// </summary>
        /// <param name="app">The ASP.NET Core application builder.</param>
        /// <param name="configuration">
        /// The delegate allowing to configure the OWIN/Katana
        /// pipeline before adding it in the ASP.NET Core application.
        /// </param>
        /// <returns>The ASP.NET Core application builder.</returns>
        public static IApplicationBuilder UseKatana(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action<IAppBuilder> configuration) {
            return app.UseOwin(setup => setup(next => {
                var builder = new AppBuilder();
                var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>();

                var properties = new AppProperties(builder.Properties);
                properties.AppName = app.ApplicationServices.GetService<IHostingEnvironment>()?.ContentRootPath;
                properties.OnAppDisposing = lifetime?.ApplicationStopping ?? CancellationToken.None;
                properties.DefaultApp = next;

                configuration(builder);

                return builder.Build<Func<IDictionary<string, object>, Task>>();
            }));
        }
        private void ConfigurePipeline(AppFunc next, string fullPath)
        {
            Console.WriteLine("Configuring pipeline...");
            try
            {
                string index = string.Format(
                    "<HTML><HEAD><TITLE>Dynamic Middleware</TITLE></HEAD><BODY><p>Edit {0} and refresh to see below links change.</p>",
                    fullPath);
                var allLines = File.ReadAllLines(fullPath);

                var app = new AppBuilder();
                foreach(var line in allLines)
                {
                    var paths = line.Split(';');
                    app.UseDirectoryBrowser(new DirectoryBrowserOptions
                    {
                        RequestPath = new PathString(paths[0]),
                        FileSystem = new PhysicalFileSystem(paths[1])
                    });
                    index += string.Format("<a href='{0}'>{0}</a><br>", paths[0]);
                    Console.WriteLine("Directory {0} on {1}", paths[1], paths[0]);
                }
                app.Use(async (ctx, next2) =>
                {
                    if(ctx.Request.Path.Value == "/")
                    {
                        await ctx.Response.WriteAsync(index);
                    }
                    await next2();
                });
                app.Run(ctx => next(ctx.Environment));
                _dynamicAppFunc = app.Build();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                _dynamicAppFunc = async env =>
                {
                    var context = new OwinContext(env);
                    context.Response.StatusCode = 500;
                    context.Response.ReasonPhrase = "Internal server error";
                    await context.Response.WriteAsync(ex.Message);
                };
            }
        }
Esempio n. 29
0
        public IDisposable Start()
        {
            SubscribeDomainEvents();
            _logger.Info("Application initialized");

            var owinBuilder = new AppBuilder();
            var startup = new Startup();
            OwinServerFactory.Initialize(owinBuilder.Properties);
            startup.Configuration(owinBuilder);

            var serverBuilder = ServerBuilder.New()
                .SetEndPoint(_endpoint)
                .SetOwinApp(owinBuilder.Build());

            var server = serverBuilder.Build();
            server.Start();

            _logger.Info("Host started at {0}", _endpoint);
            return server;
        }
        public async Task Should_get_OK()
        {
            var app = new AppBuilder();
            new ExampleStartup().Configuration(app);
            var appFunc = app.Build();

            var handler = new OwinHttpMessageHandler(appFunc)
            {
                UseCookies = true,
                AllowAutoRedirect = true
            };
            using(var httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri("http://localhost")
            })
            {
                var response = await httpClient.GetAsync("/test");

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }