Example #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            app.UseIISPlatformHandler();
            app.UseStaticFiles();
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            // loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loggerFactory.AddConsole();
            // loggerFactory.AddDebug();



            app.UseSession();
            //// uncomment these lines to use the Middleware sample
            //app.UseHeaderMiddleware();
            //app.UseHeading1Middleware();


            app.Map("/home2", homeApp =>
            {
                homeApp.Run(async context =>
                {
                    HomeController controller =
                        app.ApplicationServices.GetService <HomeController>();
                    int statusCode = await controller.Index(context);
                    context.Response.StatusCode = statusCode;
                });
            });

            app.Map("/session", sessionApp =>
            {
                sessionApp.Run(async context =>
                {
                    await SessionSample.SessionAsync(context);
                });
            });

            PathString remaining;

            app.MapWhen(context => context.Request.Path.StartsWithSegments("/configuration", out remaining),
                        configApp =>
            {
                configApp.Run(async context =>
                {
                    if (remaining.StartsWithSegments("/appsettings"))
                    {
                        await ConfigSample.AppSettings(context, Configuration);
                    }
                    else if (remaining.StartsWithSegments("/database"))
                    {
                        await ConfigSample.ReadDatabaseConnection(context, Configuration);
                    }
                    else if (remaining.StartsWithSegments("/secret"))
                    {
                        await ConfigSample.UserSecret(context, Configuration);
                    }
                });
            });


            app.Map("/configuration", configApp =>
            {
                configApp.Run(async context =>
                {
                    await ConfigSample.ReadDatabaseConnection(context, Configuration);
                });
            });

            //// uncomment this app.Run invocation to active the Hello, World!output
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});

            //// uncomment this app.Run invocation for the first Request and Response sample
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync(RequestAndResponseSample.GetRequestInformation(context.Request));
            //});


            //// uncomment this app.Run invocation for the custom routing
            //app.Run(async (context) =>
            //{
            //    if (context.Request.Path.Value.ToLower() == "/home")
            //    {
            //        HomeController controller =
            //          app.ApplicationServices.GetService<HomeController>();
            //        int statusCode = await controller.Index(context);
            //        context.Response.StatusCode = statusCode;
            //        return;
            //    }

            //    string result = string.Empty;
            //    switch (context.Request.Path.Value.ToLower())
            //    {
            //        case "/header":
            //            result = RequestAndResponseSample.GetHeaderInformation(context.Request);
            //            break;
            //        case "/add":
            //            result = RequestAndResponseSample.QueryString(context.Request);
            //            break;
            //        case "/content":
            //            result = RequestAndResponseSample.Content(context.Request);
            //            break;
            //        case "/encoded":
            //            result = RequestAndResponseSample.ContentEncoded(context.Request);
            //            break;
            //        case "/form":
            //            result = RequestAndResponseSample.GetForm(context.Request);
            //            break;
            //        case "/writecookie":
            //            result = RequestAndResponseSample.WriteCookie(context.Response);
            //            break;
            //        case "/readcookie":
            //            result = RequestAndResponseSample.ReadCookie(context.Request);
            //            break;
            //        case "/json":
            //            result = RequestAndResponseSample.GetJson(context.Response);
            //            break;
            //        default:
            //            result = RequestAndResponseSample.GetRequestInformation(context.Request);
            //            break;
            //    }
            //    await context.Response.WriteAsync(result);
            //});

            // uncomment to use the home controller
            app.Run(async(context) =>
            {
                if (context.Request.Path.Value.ToLower() == "/home")
                {
                    HomeController controller =
                        app.ApplicationServices.GetService <HomeController>();
                    int statusCode = await controller.Index(context);
                    context.Response.StatusCode = statusCode;
                    return;
                }
            });
        }
Example #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            app.UseStaticFiles();
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            // loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loggerFactory.AddConsole();
            // loggerFactory.AddDebug();



            app.UseSession();
            // uncomment these lines to use the Middleware sample
            // app.UseHeaderMiddleware();
            // app.UseHeading1Middleware();


            app.Map("/home2", homeApp =>
            {
                homeApp.Run(async context =>
                {
                    HomeController controller =
                        app.ApplicationServices.GetService <HomeController>();
                    await controller.Index(context);
                });
            });

            app.Map("/session", sessionApp =>
            {
                sessionApp.Run(async context =>
                {
                    await SessionSample.SessionAsync(context);
                });
            });

            PathString remaining;

            app.MapWhen(context => context.Request.Path.StartsWithSegments("/configuration", out remaining),
                        configApp =>
            {
                configApp.Run(async context =>
                {
                    if (remaining.StartsWithSegments("/appsettings"))
                    {
                        await ConfigSample.AppSettings(context, Configuration);
                    }
                    else if (remaining.StartsWithSegments("/database"))
                    {
                        await ConfigSample.ReadDatabaseConnection(context, Configuration);
                    }
                    else if (remaining.StartsWithSegments("/secret"))
                    {
                        await ConfigSample.UserSecret(context, Configuration);
                    }
                });
            });


            app.Map("/configuration", configApp =>
            {
                configApp.Run(async context =>
                {
                    await ConfigSample.ReadDatabaseConnection(context, Configuration);
                });
            });

            //// uncomment this app.Run invocation to active the Hello, World! output
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});

            //// uncomment this app.Run invocation for the first Request and Response sample
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync(RequestAndResponseSample.GetRequestInformation(context.Request));
            //});


            //// uncomment this app.Run invocation for the custom routing
            //app.Run(async (context) =>
            //{
            //    if (context.Request.Path.Value.ToLower() == "/home")
            //    {
            //        HomeController controller =
            //          app.ApplicationServices.GetService<HomeController>();
            //        int statusCode = await controller.Index(context);
            //        context.Response.StatusCode = statusCode;
            //        return;
            //    }
            //}

            //// uncomment this app.Run invocation for request/response samples
            //app.Run(async (context) =>
            //{
            //    string result = string.Empty;
            //    switch (context.Request.Path.Value.ToLower())
            //    {
            //        case "/header":
            //            result = RequestAndResponseSample.GetHeaderInformation(context.Request);
            //            break;
            //        case "/add":
            //            result = RequestAndResponseSample.QueryString(context.Request);
            //            break;
            //        case "/content":
            //            result = RequestAndResponseSample.Content(context.Request);
            //            break;
            //        case "/encoded":
            //            result = RequestAndResponseSample.ContentEncoded(context.Request);
            //            break;
            //        case "/form":
            //            result = RequestAndResponseSample.GetForm(context.Request);
            //            break;
            //        case "/writecookie":
            //            result = RequestAndResponseSample.WriteCookie(context.Response);
            //            break;
            //        case "/readcookie":
            //            result = RequestAndResponseSample.ReadCookie(context.Request);
            //            break;
            //        case "/json":
            //            result = RequestAndResponseSample.GetJson(context.Response);
            //            break;
            //        default:
            //            result = RequestAndResponseSample.GetRequestInformation(context.Request);
            //            break;
            //    }
            //    await context.Response.WriteAsync(result);
            //});

            //// uncomment to use the home controller
            //app.Run(async (context) =>
            //{
            //    if (context.Request.Path.Value.ToLower() == "/home")
            //    {
            //        HomeController controller =
            //          app.ApplicationServices.GetService<HomeController>();
            //        int statusCode = await controller.Index(context);
            //        context.Response.StatusCode = statusCode;
            //        return;
            //    }
            //});

            app.Map("/RequestAndResponse", app1 =>
            {
                app1.Run(async(context) =>
                {
                    await context.Response.WriteAsync(
                        RequestAndResponseSample.GetRequestInformation(context.Request));
                });
            });

            app.Map("/RequestAndResponse2", app1 =>
            {
                app1.Run(async(context) =>
                {
                    string result = string.Empty;
                    switch (context.Request.Path.Value.ToLower())
                    {
                    case "/header":
                        result = RequestAndResponseSample.GetHeaderInformation(context.Request);
                        break;

                    case "/add":
                        result = RequestAndResponseSample.QueryString(context.Request);
                        break;

                    case "/content":
                        result = RequestAndResponseSample.Content(context.Request);
                        break;

                    case "/encoded":
                        result = RequestAndResponseSample.ContentEncoded(context.Request);
                        break;

                    case "/form":
                        result = RequestAndResponseSample.GetForm(context.Request);
                        break;

                    case "/writecookie":
                        result = RequestAndResponseSample.WriteCookie(context.Response);
                        break;

                    case "/readcookie":
                        result = RequestAndResponseSample.ReadCookie(context.Request);
                        break;

                    case "/json":
                        result = RequestAndResponseSample.GetJson(context.Response);
                        break;

                    default:
                        result = RequestAndResponseSample.GetRequestInformation(context.Request);
                        break;
                    }
                    await context.Response.WriteAsync(HtmlHelper.DocType() + HtmlHelper.HtmlStart() + HtmlHelper.Head() + HtmlHelper.BodyStart());
                    await context.Response.WriteAsync(result);
                    await context.Response.WriteAsync(HtmlHelper.BodyEnd() + HtmlHelper.HtmlEnd());
                });
            });

            // contrary to the sample as it is written in the book I've made it now easier for you
            // to start all the different parts by adding this list
            // This required minor changes to the code samples. However, you can comment the following code block
            // and uncomment the specific parts as described in the book
            app.Run(async(context) =>
            {
                var sb = new StringBuilder();
                sb.Append(HtmlHelper.DocType() + HtmlHelper.HtmlStart() + HtmlHelper.Head() + HtmlHelper.BodyStart());
                sb.Append("<ul>");
                sb.Append(@"<li><a href=""/hello.html"">Static Files</a> - requires UseStaticFiles</li>");
                sb.Append(@"<li><a href=""/RequestAndResponse"">Request and Response</a>");
                sb.Append("<li>Request and Response 2");
                sb.Append("<ul>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/header"">Header</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/add?x=3&y=4"">Add</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/content?data=sample"">Content</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/content?data=<h1>sample</h1>"">HTML Content</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/content?data=<script>alert('hacker');</script>"">Bad Content</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/encoded?data=<h1>sample</h1>"">Encoded content</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/encoded?data=<script>alert('hacker');</script>"">Encoded bad Content</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/form"">Form</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/writecookie"">Write cookie</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/readcookie"">Read cookie</a></li>");
                sb.Append(@"<li><a href=""/RequestAndResponse2/json"">JSON</a></li>");
                sb.Append("</ul>");
                sb.Append("</li>");
                sb.Append(@"<li><a href=""/home2"">Home Controller with dependency injection</a></li>");
                sb.Append(@"<li><a href=""/session"">Session</a></li>");
                sb.Append("<li>Configuration");
                sb.Append("<ul>");
                sb.Append(@"<li><a href=""/configuration/appsettings"">Appsettings</a></li>");
                sb.Append(@"<li><a href=""/configuration/database"">Database</a></li>");
                sb.Append(@"<li><a href=""/configuration/secret"">Secrets  </a></li>");
                sb.Append("</ul>");
                sb.Append("</li>");
                sb.Append("</ul>");
                sb.Append(HtmlHelper.BodyEnd() + HtmlHelper.HtmlEnd());
                await context.Response.WriteAsync(sb.ToString());
            });
        }
        //通过依赖注入接收参数
        //IWebHostEnvironment允许访问环境的名称,内容的根路径(源代码目录),web的根路径(wwwroot),默认提供程序是PhysicalFileProvider
        //IApplicationBuilder接口用于向HTTP请求管道添加中间件,调用Use方法时可以构建HTTP请求管,来响应请求时应该做什么
        //Use方法使用FluentAPI,返回IApplicationBuilder,可以很容易将多个中间件对象添加到管道中
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //检测是否Development环境
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            //再写入任何响应之前,需要调用UseSession
            app.UseSession();

            //自定义的中间件
            app.UseHeaderMiddleware();

            PathString remainingPath;

            //out remainingPath是MapWhen中/Configuration后面的路径赋值给remainingPath,然后在下面逻辑判断具体去哪一个页面
            app.MapWhen(context => context.Request.Path.StartsWithSegments("/Configuration", out remainingPath), configurationApp =>
            {
                configurationApp.Run(async context =>
                {
                    var configSample = app.ApplicationServices.GetService <ConfigurationSample>();
                    if (remainingPath.StartsWithSegments("/appsettings"))
                    {
                        await configSample.ShowApplicationSettingsAsync(context);
                    }
                    else if (remainingPath.StartsWithSegments("/colons"))
                    {
                        await configSample.ShowApplicationSettingsUsingColonsAsync(context);
                    }
                    else if (remainingPath.StartsWithSegments("/database"))
                    {
                        await configSample.ShowConnectionStringSettingAsync(context);
                    }
                    else if (remainingPath.StartsWithSegments("/stronglytyped"))
                    {
                        await configSample.ShowApplicationSettingsStronglyTyped(context);
                    }
                });
            });

            app.Map("/Session", sessionApp =>
            {
                sessionApp.Run(async context =>
                {
                    await SessionSample.SessionAsync(context);
                });
            });

            app.Map("/Home", homeApp =>
            {
                homeApp.Run(async context =>
                {
                    //homeApp.ApplicationServices返回IServiceProvider注入HomeController的实现
                    HomeController controller = homeApp.ApplicationServices.GetService <HomeController>();
                    await controller.Index(context);
                });
            });

            //Map实现路由
            app.Map("/RequestAndResponse", app1 =>
            {
                app1.Run(async context =>
                {
                    //响应返回请求的信息
                    //await context.Response.WriteAsync(RequestAndResponseSamples.GetRequestInformation(context.Request));
                    context.Response.ContentType = "text/html";
                    string result = string.Empty;

                    //根据请求的地址来调用不同的方法
                    switch (context.Request.Path.Value.ToLower())
                    {
                    case "/header":
                        result = RequestAndResponseSamples.GetHeaderInformation(context.Request);
                        break;

                    case "/add":
                        result = RequestAndResponseSamples.QueryString(context.Request);
                        break;

                    case "/content":
                        result = RequestAndResponseSamples.Content(context.Request);
                        break;

                    case "/encoded":
                        result = RequestAndResponseSamples.ContentEncoded(context.Request);
                        break;

                    case "/form":
                        result = RequestAndResponseSamples.GetForm(context.Request);
                        break;

                    case "/writecookie":
                        result = RequestAndResponseSamples.WriteCookie(context.Response);
                        break;

                    case "/readcookie":
                        result = RequestAndResponseSamples.ReadCookie(context.Request);
                        break;

                    case "/json":
                        result = RequestAndResponseSamples.GetJson(context.Response);
                        break;

                    default:
                        result = RequestAndResponseSamples.GetRequestInformation(context.Request);
                        break;
                    }

                    await context.Response.WriteAsync(result);
                });
            });

            //允许客户端请求wwwroot中的静态文件
            app.UseStaticFiles();

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });

            //app.UseRouting();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapGet("/", async context =>
            //    {
            //        await context.Response.WriteAsync("Hello World!");
            //    });
            //});

            //Run()方法在请求管道中注册最后一个中间件,方法参数是RequestDelegate类型的委托,接受HttpContext参数,返回一个Task
            //使用HttpContext可以访问来自浏览器的请求,并可以发送响应
            //app.Run(async (context) =>
            //{
            //    string[] lines = new[]
            //    {
            //        @"<ul>",
            //          @"<li><a href=""/hello.html"">Static Files</a> - requires UseStaticFiles</li>",
            //          @"<li>Request and Response",
            //            @"<ul>",
            //              @"<li><a href=""/RequestAndResponse"">Request and Response</a></li>",
            //              @"<li><a href=""/RequestAndResponse/header"">Header</a></li>",
            //              @"<li><a href=""/RequestAndResponse/add?x=38&y=4"">Add</a></li>",
            //              @"<li><a href=""/RequestAndResponse/content?data=sample"">Content</a></li>",
            //              @"<li><a href=""/RequestAndResponse/content?data=<h1>Heading 1</h1>"">HTML Content</a></li>",
            //              @"<li><a href=""/RequestAndResponse/content?data=<script>alert('hacker');</script>"">Bad Content</a></li>",
            //              @"<li><a href=""/RequestAndResponse/encoded?data=<h1>sample</h1>"">Encoded content</a></li>",
            //              @"<li><a href=""/RequestAndResponse/encoded?data=<script>alert('hacker');</script>"">Encoded bad Content</a></li>",
            //              @"<li><a href=""/RequestAndResponse/form"">Form</a></li>",
            //              @"<li><a href=""/RequestAndResponse/writecookie"">Write cookie</a></li>",
            //              @"<li><a href=""/RequestAndResponse/readcookie"">Read cookie</a></li>",
            //              @"<li><a href=""/RequestAndResponse/json"">JSON</a></li>",
            //            @"</ul>",
            //          @"</li>",
            //          @"<li><a href=""/Home"">Home Controller with dependency injection</a></li>",
            //          @"<li><a href=""/abc/xyz/42hello42/foobar"">MapWhen with hello in the URL</a></li>",
            //          @"<li><a href=""/Session"">Session</a></li>",
            //          @"<li>Configuration",
            //            @"<ul>",
            //              @"<li><a href=""/Configuration/appsettings"">Appsettings</a></li>",
            //              @"<li><a href=""/Configuration/colons"">Using Colons</a></li>",
            //              @"<li><a href=""/Configuration/database"">Database</a></li>",
            //              @"<li><a href=""/Configuration/stronglytyped"">Strongly Typed</a></li>",
            //            @"</ul>",
            //          @"</li>",
            //        @"</ul>"
            //    };

            //    var sb = new StringBuilder();
            //    foreach (var line in lines)
            //    {
            //        sb.Append(line);
            //    }
            //    string html = sb.ToString().HtmlDocument("Web Sample App");

            //    await context.Response.WriteAsync(html);
            //});
        }