当前位置: 移动技术网 > IT编程>开发语言>.net > 浅谈ASP.NET Core 2.0 中间件(译)

浅谈ASP.NET Core 2.0 中间件(译)

2017年11月02日  | 移动技术网IT编程  | 我要评论

红楼活该你倒霉,221.214.92.86,谢仁馨

问题

如何创建一个最简单的asp.net core中间件?

答案

使用vs创建一个asp.net core 2.0的空项目,注意startup.cs中的configure()方法:

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
  app.run(async (context) =>
  {
    await context.response.writeasync("hello world! (run)");
  });
}

比较好的创建请求管道的方法是使用iapplicationbuilder上的扩展方法:

public static void runhelloworld(this iapplicationbuilder app)
{
  app.run(async (context) =>
  {
    await context.response.writeasync("hello world! (run)");
  });
}
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
  app.runhelloworld();
}

运行,此时页面显示:

上面我们使用iapplicationbuilder.run()来配置中间件,另外一种方法是iapplicationbuilder.use():

public static void usehelloworld(this iapplicationbuilder app)
{
  app.use(async (context, next) =>
  {
    await context.response.writeasync("hello world! (use)\n");
    await next();
  });
}
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
  app.usehelloworld();
  app.runhelloworld();
}

运行,此时页面显示:

将中间件作为单独的类定义是更好的实践方法:

public class helloworldmiddleware
{
  private readonly requestdelegate _next;

  public helloworldmiddleware(requestdelegate next)
  {
    _next = next;
  }

  public async task invoke(httpcontext context)
  {
    await context.response.writeasync("hello world! (use in class)\n");
    await _next(context);
  }
}


public static class usehelloworldinclassextensions
{
  public static iapplicationbuilder usehelloworldinclass(this iapplicationbuilder app)
  {
    return app.usemiddleware<helloworldmiddleware>();
  }
}

public void configure(iapplicationbuilder app, ihostingenvironment env)
{
  app.usehelloworld();
  app.usehelloworldinclass();
  app.runhelloworld();
}

运行,此时页面显示:

讨论

中间件是一个拦截http请求和响应消息的组件。我们通过创建这些组件链,来为我们的应用程序创建一个请求管道。

我们通过configure()方法的iapplicationbuilder参数来创建这个请求管道,iapplicationbuilder参数有如下方法:

  1. run():添加中间件并终止请求管道(也就是说不再调用下一个中间件)。
  2. use():添加中间件,使用lambda表达式或者一个具体的类。
  3. map():根据请求路径添加中间件。

run

这个方法接受requestdelegate委托作为参数,当委托方法被调用时接受httpcontext参数。这个委托方法返回void,因为它会终止请求管道。

use

这个方法接受func委托作为参数,此委托方法有两个参数,分别是httpcontext和指向下一个中间件的next,返回空(task)。如果没有调用下一个中间件,就会终止请求管道(和run效果一样)。

usermiddleware

当通过单独类创建中间件时,我们使用usemiddleware方法,并将具体的实现类型作为泛型参数。

在中间件类中,有两个部分很重要:

1. 构造函数接受requestdelegate。当调用此委托时会将当前请求传入下一个中间件。

2. 它拥有一个invoke方法,接收httpcontext参数并返回空(task)。当需要用到中间件时,框架会主动调用这个方法。

注:在单独类中实现中间件,并用usemiddleware封装起来是最佳实践。

扩展方法

需要注意扩展方法的不同之处,runxxx不会返回值,而usexxx会返回值(iapplicationbuilder)。这是因为run()终止请求管道,而use()可能会链接到其他的中间件。

顺序

中间件按照它们在configure()方法出现的顺序依次被调用。而返回到客户端的响应也会经历相同的中间件管道。

原文:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网