第一次接触Core 6.0

1.采用minimal API构件ASP.NET CORE程序

RequestDelegate handler = context => context.Response.WriteAsync("Hello,World!"); //中间件委托
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);//通过静态工厂方法,创建应用程序构造类实例
WebApplication app = builder.Build();//构建应用程序类
app.Run(handler);//把handle中间件插入到应用程序管道内。
app.Run();//启动应用程序


// public delegate Task RequestDelegate(HttpContext context); RequestDeleate就是一个委托。

2.一步创建WebApplication

WebApplication app = WebApplication.Create(args);//直接通过应用程序类的静态工厂方法,创建对应的应用程序实例。
app.Run(HandleAsync);
app.Run();
//这个的本质就是RequestDelegate委托
static Task HandleAsync(HttpContext httpContext) => httpContext.Response.WriteAsync("Hello,World!1");

3.构造应用程序之前就添加中间件

WebApplication app = WebApplication.Create(args);
IApplicationBuilder appBuilder = app;
appBuilder.Use(HelloMiddleware).Use(WorldMiddleware);//Use方法把中间件添加到应用程序管道内(按先后顺序插入)。
app.Run();

static RequestDelegate HelloMiddleware(RequestDelegate next) =>
    async httpContext =>
    {
        await httpContext.Response.WriteAsync("Hello, ");
        await next(httpContext);
    };
static RequestDelegate WorldMiddleware(RequestDelegate next) => async httpContext => await httpContext.Response.WriteAsync("World!");

4.使用中间件变体委托

WebApplication app = WebApplication.Create(args);
IApplicationBuilder appBuilder = app;
appBuilder.Use(HelloMiddleware).Use(WorldMiddleware);
app.Run();

static async Task HelloMiddleware(HttpContext httpContext, RequestDelegate next) //Q.这里的Next委托是怎么确定的?
{
    await httpContext.Response.WriteAsync("Hello, ");
    await next(httpContext);
};
static async Task WorldMiddleware(HttpContext httpContext, RequestDelegate next) => await httpContext.Response.WriteAsync("World!"); //Q.这里的Next委托是怎么确定的?
WebApplication app = WebApplication.Create(args);
IApplicationBuilder appBuilder = app;
appBuilder.Use(HelloMiddleware).Use(WorldMiddleware);
app.Run();

static async Task HelloMiddleware(HttpContext httpContext, Func<Task> next)  //Q.这里的Next委托是怎么确定的?  
{
    await httpContext.Response.WriteAsync("Hello, ");
    await next();
};
static async Task WorldMiddleware(HttpContext httpContext, Func<Task> next) => await httpContext.Response.WriteAsync("World!");  //Q.这里的Next委托是怎么确定的?

5.使用强类型中间件

using APP;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IGreeter, Greeter>().AddSingleton<GreetingMiddleware>(); //.Configure<GreetingOptions>(builder.Configuration.GetSection("greeting")); //依赖注入单例对象。
var app = builder.Build();
app.UseMiddleware<GreetingMiddleware>();
app.Run();

namespace APP
{
    public interface IGreeter
    {
        string Greet(DateTimeOffset time);
    }

    public class Greeter : IGreeter
    {
        private readonly IConfiguration _configuration;

        public Greeter(IConfiguration configuration) => _configuration = configuration.GetSection("greeting");
        public string Greet(DateTimeOffset time) => time.Hour switch
        {
            var h when h >= 5 && h < 12 => _configuration["morning"],
            var h when h >= 12 && h < 17 => _configuration["afternoon"],
            _ => _configuration["evening"]

        };
    }public class GreetingMiddleware : IMiddleware
    {
        private readonly IGreeter _greeter;
        public GreetingMiddleware(IGreeter greeter) => _greeter = greeter;
        public Task InvokeAsync(HttpContext context, RequestDelegate next) => context.Response.WriteAsync(_greeter.Greet(DateTimeOffset.UtcNow));
    }
   

    public class GreetingOptions
    {
      public string Morning { get; set; }
      public string Afternoon { get; set; }
      public string Evening { get; set; }
    }


}

也可以改成下面的这种形式

    /// <summary>
    /// 也可以改写成下面这样,构造函数注入
    /// </summary>
    public class GreetingMiddleware //这里特别注意,我并没有实现IMiddleware,也是可以直接当成中间件来使用的。
    {
        private readonly IGreeter _greeter;
        public GreetingMiddleware(IGreeter greeter, RequestDelegate next) => _greeter = greeter;
        public Task InvokeAsync(HttpContext context) => context.Response.WriteAsync(_greeter.Greet(DateTimeOffset.UtcNow));
    }

    /// <summary>
    /// 也可以改成下面这样,方法注入
    /// </summary>
    public class GreetingMiddleware
    {
        public GreetingMiddleware(RequestDelegate next) { }
        public Task InvokeAsync(HttpContext context, IGreeter greeter) => context.Response.WriteAsync(greeter.Greet(DateTimeOffset.UtcNow));
    }

 

知识点:
RequestDelegate --中间件委托
IMiddleware --中间件接口
WebApplication --应用程序类,用于配置HTTP管道和Web应用程序。
WebApplicationBuilder --应用程序类的建造者。
HttpContext--当前上下文类(主要包含HttpRequest和HttpResponse属性)

Microsoft.NET.Sdk --控制台应用程序
Microsoft.NET.Sdk.Web --Web应用程序(挂载在控制台上)

ImplicitUsings属性与C#10提供的一个叫做"全局命名空间"有关
Nullable属性与一个名为"空值(null)验证"的特性有关。
.NET6项目控制台,可以直接没有引用、命名空间和类的原因是与C#10提供的一个被"顶级语句(Top-level Statements)"的特性有关。

中间件的定义要求
中间件类型需要定义一个公共实例类型(静态类型无效),其构造函数可以注入任意的依赖服务看,单必须包含一个RequestDelegate类型的参数该参数表示由后续中间件构成的管道,当前中间件利用它将请求分发给后续管道作进一步处理。
针对请求的处理实现在一个命名为InvokeAsync或者Invoke方法中,该方法返回类型为Task,第一个参数并绑定为当前的HttpContext上下文。

 

参考链接

https://www.cnblogs.com/artech/p/inside-asp-net-core-6-1.html#s101

posted @ 2022-03-07 18:35  落落落落码  阅读(133)  评论(0编辑  收藏  举报