调用时访问中间件选项

时间:2018-12-03 16:09:12

标签: c# asp.net-core

我正在创建一个自定义的中间件元素,但无法弄清楚如何将Options对象传递给中间件并通过Invoke方法访问它们。

配置

public class MiddleConfig
{
    private readonly ICollection<string> _c;

    public MiddleConfig()
    {
        _c = new Collection<string>();
    }

    public void AddPath(string path)
    {
        _c.Add(path);
    }

    public IEnumerable<string> Paths => _c;
}

MiddleConfig

public class Middle
{
    private readonly RequestDelegate _next;
    private readonly MiddleConfig _opt = new MiddleConfig();

    public Middle(RequestDelegate next, MiddleConfig options)
    {
        _opt = options;
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await _next.Invoke(context);
    }
}

扩展名

public static IServiceCollection AddLCPathControl(this IServiceCollection services, Action<MiddleConfig> options)
{
    MiddleConfig opt = new MiddleConfig();
    options.Invoke(opt);

    return services.AddScoped<Middle>();
}

1 个答案:

答案 0 :(得分:1)

结果是我使用了错误的方法来添加中间件。

更改为将中间件添加到ApplicationBuilder并使用UseMiddleware <>(),该中间件无法按照我的意愿进行选择。

扩展名

public static class IServiceCollectionExtension
{
    public static IApplicationBuilder UseLCPathControl(this IApplicationBuilder services, string path)
    {
        return services.UseLCPathControl(o => o.AddPath(path));
    }

    public static IApplicationBuilder UseLCPathControl(this IApplicationBuilder builder, Action<MiddleConfig> options)
    {
        MiddleConfig opt = new MiddleConfig();
        options.Invoke(opt);

        return builder.UseMiddleware<Middle>(opt);
    }
}

public class Middle
{
    private readonly RequestDelegate _next;
    private readonly MiddleConfig _opt = new MiddleConfig();

    public Middle(RequestDelegate next, MiddleConfig options)
    {
        _opt = options;
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await _next.Invoke(context);
    }
}

MiddleConfig

public class MiddleConfig
{
    private readonly ICollection<string> _c;

    public MiddleConfig()
    {
        _c = new Collection<string>();
    }

    public void AddPath(string path)
    {
        _c.Add(path);
    }

    public IEnumerable<string> Paths => _c;
}