【问题标题】:ASP.NET Core OWIN MiddlewareASP.NET Core OWIN 中间件
【发布时间】:2018-06-01 07:09:12
【问题描述】:

我有一个 ASP.NET Core 应用程序和一个简单的 OWIN 中间件来检查一些数据。但我只想在请求页面时运行中间件。现在它在请求资产时运行,例如图像、css 等。

如何让 owin 中间件代码只在页面请求时执行?

注册:

app.UseSiteThemer();

Site Themer 扩展类:

public static class SiteThemerExtensions
{
    public static IApplicationBuilder UseSiteThemer(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<SiteThemerMiddleware>();
    }
}

OWIN 中间件:

public class SiteThemerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ISiteService _siteService;

    public SiteThemerMiddleware(RequestDelegate next, ISiteService siteService)
    {
        _siteService = siteService;
        _next = next;
        //_logger = loggerFactory.CreateLogger<SiteThemerMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        await Task.Run(() =>
         {

             Console.Write("OWIN Hit");
         });


        //_logger.LogInformation("Handling request: " + context.Request.Path);
        await _next.Invoke(context);
        //_logger.LogInformation("Finished handling request.");
    }
}

【问题讨论】:

  • 在管道中添加它比静态文件处理程序中间件晚?
  • 向我们展示您如何注册中间件。关键可能是从注册 .Use 切换到注册 .Map 但没有只是猜测的代码。
  • @tpeczek 我继续更新我的代码,谢谢!

标签: c# asp.net-core owin


【解决方案1】:

您可以在这里使用 ASP.NET Core 管道的两个方面来实现您的目标:排序和分支。

关于排序的规则非常简单——添加中间件的顺序就是它们将要执行的顺序。这意味着如果像您这样的中间件被放置在一些可以结束管道的中间件(例如静态文件)之后,如果发生这种情况,它将不会被调用。

为了分支管道,您可以使用MapMapWhen 方法。第一个基于路径分支管道,而另一个基于谓词。使用MapMapWhen 添加的中间件只有在满足分支条件时才会被调用。

您可以阅读有关管道here的更多详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2014-04-09
    • 2020-10-09
    • 2018-02-08
    相关资源
    最近更新 更多