Exemplo n.º 1
0
        public async Task Can_use_with_app_base_with_web()
        {
            _webBuilder.Register("/test", async context =>
            {
                await context.Response.WriteAsync("Hello, World! " + context.Request.Path + " " + context.Request.PathBase);
            });

            using (var host = _webBuilder.BuildWebHost("", 5003))
            {
                host.Listen();
                using (var client = host.CreateClient())
                {
                    var responseMessage = await client.GetAsync("/test");

                    responseMessage.EnsureSuccessStatusCode();
                    var response = await responseMessage.Content.ReadAsStringAsync();

                    Assert.Equal("Hello, World! /test ", response);
                }
            }

            using (var host = _webBuilder.BuildWebHost("/appbase", 5003))
            {
                host.Listen();
                using (var client = host.CreateClient())
                {
                    var responseMessage = await client.GetAsync("/test");

                    responseMessage.EnsureSuccessStatusCode();
                    var response = await responseMessage.Content.ReadAsStringAsync();

                    Assert.Equal("Hello, World! /test /appbase", response);
                }
            }
        }
Exemplo n.º 2
0
        public async Task Can_export_path_without_extension()
        {
            _webBuilder.Register("/test",
                                 context => context.Response.WriteAsync("test content"));
            using (var host = _webBuilder.BuildVirtualHost())
            {
                await _hostExporter.Export(host, _directory);
            }

            File.Exists(Path.Combine(_directory, "test", "index.html")).Should().BeTrue();
        }
Exemplo n.º 3
0
        private static void RegisterFileInfo(this IWebBuilder webBuilder, IFileProvider fileProvider, PathString prefix, string basePath, IFileInfo fileInfo, RegisterOptions options)
        {
            if (fileInfo.IsDirectory)
            {
                var content = fileProvider.GetDirectoryContents(Path.Combine(basePath, fileInfo.Name));

                if (content == null || !content.Exists)
                {
                    return;
                }

                foreach (var child in content)
                {
                    webBuilder.RegisterFileInfo(fileProvider, prefix, Path.Combine(basePath, fileInfo.Name), child, options);
                }
            }
            else
            {
                var filePath    = Path.Combine(basePath, fileInfo.Name);
                var requestPath = new PathString().Add(prefix)
                                  .Add(filePath);

                if (options != null && options.Matcher != null)
                {
                    if (!options.Matcher.Match(filePath.Substring(1)).HasMatches)
                    {
                        // We are ignoring this file
                        return;
                    }
                }

                var builtState = options?.State?.Invoke(prefix, requestPath, filePath, fileInfo, fileProvider);

                webBuilder.Register(requestPath, async context =>
                {
                    var env = context.RequestServices.GetRequiredService <IHostingEnvironment>();

                    var statileFileOptions = Options.Create(new StaticFileOptions());
                    statileFileOptions.Value.FileProvider          = fileProvider;
                    statileFileOptions.Value.ServeUnknownFileTypes = true;

                    var loggerFactory = context.RequestServices.GetRequiredService <ILoggerFactory>();
                    var middleware    = new StaticFileMiddleware(_ => Task.CompletedTask, env, statileFileOptions, loggerFactory);

                    var oldPath = context.Request.Path;
                    try
                    {
                        context.Request.Path = filePath;
                        await middleware.Invoke(context);
                    }
                    finally
                    {
                        context.Request.Path = oldPath;
                    }
                },
                                    builtState,
                                    /*don't convert "/file" to "/file/index.html"*/
                                    true);
            }
        }
Exemplo n.º 4
0
        public static void Redirect(this IWebBuilder webBuilder, string from, string to, object state = null, bool extractExactPath = false)
        {
            webBuilder.Register(from, async(context) =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync($@"<!DOCTYPE html>
<html lang=""en-US"">
<meta charset=""utf-8"">
<title>Redirecting&hellip;</title>
<link rel=""canonical"" href=""{context.Request.PathBase}{to}"">
<script>location=""{context.Request.PathBase}{to}""</script>
<meta http-equiv=""refresh"" content=""0; url={context.Request.PathBase}{to}"">
<meta name=""robots"" content=""noindex"">
<h1>Redirecting&hellip;</h1>
<a href=""{context.Request.PathBase}{to}"">Click here if you are not redirected.</a>
</html>");
            },
                                state,
                                extractExactPath);
        }
Exemplo n.º 5
0
        public static void RegisterMvc(this IWebBuilder webBuilder, string path, object routeData, object state = null)
        {
            webBuilder.Register(path, async context =>
            {
                var actionSelector       = context.RequestServices.GetRequiredService <IActionSelector>();
                var actionInvokerFactory = context.RequestServices.GetRequiredService <IActionInvokerFactory>();

                var routeContext = new RouteContext(context);
                if (routeData != null)
                {
                    foreach (var value in new RouteValueDictionary(routeData))
                    {
                        routeContext.RouteData.Values[value.Key] = value.Value;
                    }
                }

                var candidates = actionSelector.SelectCandidates(routeContext);
                if (candidates == null || candidates.Count == 0)
                {
                    throw new Exception("No actions matched");
                }

                var actionDescriptor = actionSelector.SelectBestCandidate(routeContext, candidates);
                if (actionDescriptor == null)
                {
                    throw new Exception("No actions matched");
                }

                var actionContext = new ActionContext(context, routeContext.RouteData, actionDescriptor);

                var invoker = actionInvokerFactory.CreateInvoker(actionContext);
                if (invoker == null)
                {
                    throw new InvalidOperationException("Couldn't create invoker");
                }

                await invoker.InvokeAsync();
            },
                                state);
        }