ASP.NET Problems and solutions of middleware with initial parameters in core 2.0

Time:2020-11-28

problem

How to ASP.NET Core 2.0 passes initial parameters to middleware?

answer

In an empty project, create a poco (plain old CLR object) to save the required parameters of middleware:


public class GreetingOptions
{
  public string GreetAt { get; set; }
  public string GreetTo { get; set; }
}

Add a middleware:


public class GreetingMiddleware
{
  private readonly RequestDelegate _next;
  private readonly GreetingOptions _options;
  public GreetingMiddleware(RequestDelegate next, GreetingOptions options)
  {
    _next = next;
    _options = options;
  }
  public async Task Invoke(HttpContext context)
  {
    var message = $"Good {_options.GreetAt} {_options.GreetTo}";
    await context.Response.WriteAsync(message);
  }
}

Answer 1: instance type

Add an extension method to configure the middleware:


public static IApplicationBuilder UseGreetingMiddleware(this IApplicationBuilder app, GreetingOptions options)
{
  return app.UseMiddleware<GreetingMiddleware>(options);
}

Using middleware:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseGreetingMiddleware(new GreetingOptions {
    GreetAt = "Morning",
    GreetTo = "Tahir"
  });
}

Answer 2: function type

Add an extension method to configure the middleware:


public static IApplicationBuilder UseGreetingMiddlewareAction(this IApplicationBuilder app, Action<GreetingOptions> optionsAction)
{
  var options = new GreetingOptions();
  optionsAction(options);

  return app.UseMiddleware<GreetingMiddleware>(options);
}

Using middleware:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseGreetingMiddlewareAction(options =>
  {
    options.GreetAt = "Morning";
    options.GreetTo = "Tahir";
  });
}

The results of the two methods are consistent.

Run, the page displays:

discuss

As we discussed earlier, it is a best practice to define Middleware in a separate class and add it to the request pipeline using an extension method. We may also need to pass in parameters to the middleware through the ASP.NET Core source code and other online examples of learning, I summed up the above two modes.

Both of these solutions are very intuitive. We encapsulate the parameters into a poco class, and then create an extension method to accept the following parameters:

1. Poco example

2. Functions to be called (poco is set in the function)

Note: poco instance is passed into middleware through constructor. The usemiddleware () method receives the variable parameter params object [] and passes these parameters into the middleware constructor.

Configuration services

These patterns can also be used to add service instances to a service container. For illustration purposes, let’s first add a service:


public interface IMessageService
{  string FormatMessage(string message);
}
public class MessageService : IMessageService
{
  private readonly GreetingOptions _options;
  public MessageService(GreetingOptions options)
  {
    _options = options;
  }
  public string FormatMessage(string message)
  {
    return $"Good {_options.GreetAt} {_options.GreetTo} - {message}";
  }
}

Add any of the following extension methods to configure the service:


public static IServiceCollection AddMessageService(this IServiceCollection services, GreetingOptions options)
{  return services.AddScoped<IMessageService>(factory => new MessageService(options));
}
public static IServiceCollection AddMessageServiceAction(this IServiceCollection services, Action<GreetingOptions> optionsAction)
{
  var options = new GreetingOptions();
  optionsAction(options);
  return services.AddScoped<IMessageService>(factory => new MessageService(options));
}

Use this service in configure():


public void ConfigureServices(IServiceCollection services)
{
  services.AddMessageService(new GreetingOptions
  {
    GreetAt = "Morning",
    GreetTo = "Tahir"
  });
  services.AddMessageServiceAction(options =>
  {
    options.GreetAt = "Morning";
    options.GreetTo = "Tahir";
  });
}

Since configureservices() is executed before configure(), we can inject this service directly in configure():


public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMessageService msg)
{
  app.Run(async (context) =>
  {
    await context.Response.WriteAsync(msg.FormatMessage("by sanshi"));
  });
}

Run, the page displays:

Click to download the source code: http://xiazai.jb51.net/201710/yuanma/MiddlewareWithParameters.rar

summary

The above is a small series for you to introduce ASP.NET Core 2.0 with initial parameters of middleware problems and solutions, I hope to help you, if you have any questions, please leave me a message, the editor will reply to you in time. Thank you very much for your support to the developeppaer website!