Ejemplo n.º 1
0
        public void ScrapeWebServerWithDynamicJS()
        {
            const string html = @"<html><head></head><body><div id=""div1"">{0}</div>
<script>
var p = document.createElement(""p"");
var text = document.createTextNode(""This is a test."");
p.appendChild(text);
var div1 = document.getElementById(""div1"");
div1.appendChild(p);
</script>
</body></html>";

            using (WebHost.StartWith("http://localhost:10002", app =>
            {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync(string.Format(html, ""));
                });
            }))
            {
                var s           = new Scraper(new Uri("http://localhost:10002"));
                var fetchedHtml = s.FetchHtml(true);
                fetchedHtml.Should().Be(string.Format(html, "<p>This is a test.</p>"));
            }
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var messageSent = new ManualResetEventSlim(false);

            using (var host = WebHost.StartWith("http://127.0.0.1:0", app =>
            {
                app.Run(async context =>
                {
                    var env = context.RequestServices.GetRequiredService <IHostEnvironment>();
                    await context.Response.WriteAsync(env.ApplicationName);
                    messageSent.Set();
                });
            }))
            {
                // Need these for test deployer to consider host deployment successful
                // The address written here is used by the client to send requests
                var addresses = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses;
                foreach (var address in addresses)
                {
                    Console.WriteLine($"Now listening on: {address}");
                }
                Console.WriteLine("Application started. Press Ctrl+C to shut down.");

                // Shut down after message sent or timeout
                messageSent.Wait(TimeSpan.FromSeconds(30));
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Start a local server to use in SpecFlow tests.
 /// </summary>
 /// <param name="baseHostUrl">Base URL to listen for requests.</param>
 /// <param name="app">The delegate that configures <see cref="IApplicationBuilder" />.</param>
 public static void StartLocalServer(Uri baseHostUrl, Action <IApplicationBuilder> app)
 {
     if (baseHostUrl == null)
     {
         throw new ArgumentNullException(nameof(baseHostUrl));
     }
     WebHostBaseUrl = baseHostUrl;
     webHost        = WebHost.StartWith(baseHostUrl.ToString(), app);
     webHost.StartAsync();
 }
Ejemplo n.º 4
0
 public StubHttpServer(string url)
 {
     webHost = WebHost.StartWith(url, app =>
     {
         app.Run(async context =>
         {
             var requestMessage  = new HttpRequestMessageFeature(context).HttpRequestMessage;
             var responseMessage = handlers.FirstOrDefault(h => h.Expression(requestMessage))?.ValueCreator();
             await ConvertToHttpResponseAsync(responseMessage, context.Response).ConfigureAwait(false);
         });
     });
 }
Ejemplo n.º 5
0
 private static void CustomApplicationBuilder()
 {
     // Using a application builder
     using (WebHost.StartWith(app =>
     {
         app.UseStaticFiles();
         app.Run(async context =>
         {
             await context.Response.WriteAsync("Hello, World!");
         });
     }))
     {
         //host.WaitForShutdown(); // TODO: https://github.com/aspnet/Hosting/issues/1022
         Console.WriteLine("Running CustomApplicationBuilder: Press any key to shutdown and start the next sample...");
         Console.ReadKey();
     }
 }
Ejemplo n.º 6
0
        public void ScrapeWebServer()
        {
            const string html = @"<html><head></head><body><a href=""foo"">bar</a></body></html>";

            using (WebHost.StartWith("http://localhost:10001", app =>
            {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync(html);
                });
            }))
            {
                var s           = new Scraper(new Uri("http://localhost:10001"));
                var fetchedHtml = s.FetchHtml(true);
                fetchedHtml.Should().Be(html);
            }
        }
Ejemplo n.º 7
0
 public void ParseLinksForUri()
 {
     using (WebHost.StartWith("http://*****:*****@"<html><body><a href=""foo"">bar</a></body></html>";
             await context.Response.WriteAsync(html);
         });
     }))
     {
         var p     = new Parser(new Uri("http://localhost:9999"));
         var links = p.Parse().GetLinks(includeEmpty: false, includeHashLink: false, includeJavaScriptLink: false);
         var link  = links.First();
         link.Href.Should().Be("foo");
         link.Value.Should().Be("bar");
     }
 }
Ejemplo n.º 8
0
 private static IDisposable BuildAppAsync(string host, Action <ObservableWebsocketOptions> configure, Action <IObservableWebsocket> onAccept) =>
 WebHost.StartWith($"http://{host}", app => app.UseWebSockets().UseObservableWebsockets(c => { configure(c); c.OnAccept(onAccept); }));
Ejemplo n.º 9
0
        public static void Main(string[] args)
        {
            //CreateWebHostBuilder(args).Build().Run();

            //CreateAnotherWebHostBuilder(args).Build().Run();

            /*
             * //通过调用 Start 方法以非阻止方式运行主机
             * var host = new WebHostBuilder().Build();
             * using (host)
             * {
             *  host.Start();
             *  Console.ReadLine();
             * }
             */

            /*
             * //如果 URL 列表传递给 Start 方法,该列表侦听指定的 URL:
             * var urls = new List<string>
             * {
             *  "http://*:5000",
             *  "http://localhost:5001"
             * };
             *
             * var host = new WebHostBuilder()
             *  .UseKestrel()
             *  .UseStartup<Startup>()
             *  .Start(urls.ToArray());
             *
             * using (host)
             * {
             *  Console.ReadLine();
             * }
             */

            /*
             * //Start(RequestDelegate app)
             * using (var host = WebHost.Start(app => app.Response.WriteAsync("Hello,Micahel!")))
             * {
             *  Console.WriteLine("Use Ctrl + C to shutdown the host......");
             *  host.WaitForShutdown();
             * }
             */

            //Start(string url, RequestDelegate app)

            /*
             * using (var host = WebHost.Start("http://localhost:8080", app => app.Response.WriteAsync("Hello,Michael!")))
             * {
             *  Console.WriteLine("Use Ctrl + C to shutdown the host...");
             *  host.WaitForShutdown();
             * }
             */

            //Start(Action<IRouteBuilder> routeBuilder)

            /*
             * using (var host = WebHost.Start(router =>
             * {
             *  router.MapGet("hello/{name}", (req, res, data) =>
             *   {
             *       return res.WriteAsync($"Hello,{data.Values["name"]}!");
             *   })
             *  .MapGet("buenosdias/{name}", (req, res, data) =>
             *   {
             *       return res.WriteAsync($"Buenos dias,{data.Values["name"]}");
             *   })
             *  .MapGet("throw/{message?}", (req, res, data) =>
             *   {
             *       throw new Exception((string)data.Values["message"] ?? "Uh oh!");
             *   })
             *  .MapGet("{greeting}/{name}", (req, res, data) =>
             *   {
             *       return res.WriteAsync($"{data.Values["greeting"]},{data.Values["name"]}!");
             *   })
             *  .MapGet("", (req, res, data) =>
             *   {
             *       return res.WriteAsync("Hello,Michael!");
             *   });
             * }))
             * {
             *  Console.WriteLine("Use Ctrl + C to shutdown the host...");
             *  host.WaitForShutdown();
             * }
             */

            /*
             * //Start(string url, Action<IRouteBuilder> routeBuilder)
             * using (var host = WebHost.Start("http://localhost:8080", router =>
             * {
             *  router.MapGet("hello/{name}", (req, res, data) =>
             *  {
             *      return res.WriteAsync($"Hello,{data.Values["name"]}!");
             *  })
             *  .MapGet("buenosdias/{name}", (req, res, data) =>
             *  {
             *      return res.WriteAsync($"Buenos dias,{data.Values["name"]}");
             *  })
             *  .MapGet("throw/{message?}", (req, res, data) =>
             *  {
             *      throw new Exception((string)data.Values["message"] ?? "Uh oh!");
             *  })
             *  .MapGet("{greeting}/{name}", (req, res, data) =>
             *  {
             *      return res.WriteAsync($"{data.Values["greeting"]},{data.Values["name"]}!");
             *  })
             *  .MapGet("", (req, res, data) =>
             *  {
             *      return res.WriteAsync("Hello,Michael!");
             *  });
             * }))
             * {
             *  Console.WriteLine("Use Ctrl + C to shutdown the host...");
             *  host.WaitForShutdown();
             * }
             */

            //StartWith(Action<IApplicationBuilder> app)

            /*
             * using (var host = WebHost.StartWith(app => app.Use(next =>
             * {
             *  return async context =>
             *  {
             *      await context.Response.WriteAsync("Hello Michael!");
             *  };
             * })))
             * {
             *  Console.WriteLine("Use Ctrl + C to shutdown the host...");
             *  host.WaitForShutdown();
             * }
             */

            //StartWith(string url, Action<IApplicationBuilder> app)
            using (var host = WebHost.StartWith("http://localhost:8080", app => app.Use(next =>
            {
                return(async context =>
                {
                    await context.Response.WriteAsync("Hello Michael!");
                });
            })))
            {
                Console.WriteLine("Use Ctrl + C to shutdown the host...");
                host.WaitForShutdown();
            }
        }