.Net微说集.netC#

ASP.NET CORE 跨平台开发从入门到实战

2017-08-20  本文已影响350人  张中华

练习代码:https://github.com/956159241/ASP.NET_CORE.git

第五章 ASP.NET CORE

5.1 ASP.NET CORE 介绍

ASP.NET Core 是一个全新的开源、跨平台框架,可以用它来构建基于网络连接的现代云应用程序,比如:Web 应用,IoT(Internet Of Things,物联网)应用和移动后端等。ASP.NET Core可以运行在 .NET Core 或完整的 .NET Framework 之上,其架构为发布到云端或本地运行的应用提供了一个最佳的开发框架,由开销很小的模块化组件构成,这就保持了你构造解决方案的灵活性。你可以跨平台地在Windows、Mac和Linux等设备上开发和运行你的 ASP.NET Core 应用。ASP.NET Core 的源代码已经在 GitHub 上托管。

5.1.1 ASP.NET CORE 应用

Program.cs

 public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            host.Run();
        }
    }
5.1.2 Startup:用来定义请求处理管道和配置应用需要的服务,该类必须是公开(public)的,而且必须含有以下两个方法。
 public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
5.1.3 服务
5.1.4 中间件
5.1.5 服务器
5.1.6 内容根目录

默认情况下,内容根目录与宿主目录应用的可执行程序的应用根目录相同;其他位置可以通过WebHostBuilder来设置。


5.1.7 网站根目录

Web根目录默认为<contentroot>/wwwroot,但是也可以通过WebHostBuilder来指定另外一个地址。

5.1.8 配置
5.1.9 环境

5.2 Application StartUp

5.2.1 实战中间件
 public class RequestIpMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public RequestIpMiddleware(RequestDelegate next, ILoggerFactory loggetFactory)
        {
            _next = next;
            _logger = loggetFactory.CreateLogger<RequestIpMiddleware>();
        }
        public async Task Invoke(HttpContext context)
        {
            _logger.LogInformation("User Ip :" +
                context.Connection.RemoteIpAddress.ToString());
            await _next.Invoke(context);
        }
    }
public static class RequestIPExtensions
    {
        public static IApplicationBuilder UseRequestIp(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestIpMiddleware>();
        }
    }

这样就编写好了一个中间件(好吧,不知所以……)

上一篇 下一篇

猜你喜欢

热点阅读