【问题标题】:Map a route to a middleware class?将路由映射到中间件类?
【发布时间】:2017-12-14 23:28:30
【问题描述】:

似乎这应该是一个简单的问题,但我一直无法通过 Google 找到解决方案。

在 ASP.NET Core 中,IHttpHandler 实现者被中间件类取代似乎很标准。旧系统的一个优点是您可以设置一个 HTTP 处理程序来响应在 web.config 中指定的路由。

因此,例如,如果我的 IHttpHandler 实现者被命名为 FooHandler,web.config 将包含如下内容:

<location path="foo">
    <system.webServer>
        <handlers>
            <add name="FooHandler" path="*" verb="*" type="FooCompany.FooProduct.FooHandler, FooCompany.FooProduct"/>
        </handlers>
    </system.webServer>
</location>

在 ASP.NET Core 中是否有这样的路由的一对一替换?我该怎么做?

编辑:新的中间件类可能类似于:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace FooCompany.FooProduct.Middleware
{
    public class FooMiddleware
    {
        private readonly RequestDelegate _next;

        public FooMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Response.StatusCode = 200;
            await context.Response.WriteAsync("OK");

            await _next.Invoke(context);
        }
    }

    public static class FooMiddlewareExtensions
    {
        public static IApplicationBuilder UseFoo(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<FooMiddleware>();
        }
    }
}

【问题讨论】:

  • 可以像builder.Map("/path", b =&gt; b.UseMiddleware&lt;FooMiddleware&gt;())一样使用IApplicationBuilder的地图扩展方法

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

您可以像这样使用 IApplicationBuilder 的 Map 扩展方法:

public static class FooMiddlewareExtensions
{
    public static IApplicationBuilder UseFoo(this IApplicationBuilder builder, string path)
    {
        return builder.Map(path, b => b.UseMiddleware<FooMiddleware>());
    }
}

您也可以在中间件中执行此操作

public class FooMiddleware
{
    private readonly RequestDelegate _next;
    private readonly PathString _path;

    public FooMiddleware(RequestDelegate next, PathString path)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Path.StartsWithSegments(path))
        {
            // jump to the next middleware
            await _next.Invoke(context);
        }

        // do your stuff
    }
}

【讨论】:

  • 除了路径未分配给 _path 并在之后使用之外,在 .Net Core 3.0 中它会在扩展方法中引发异常: System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.尝试激活 'FooMiddleware' 时出现 Http.PathString'。可能缺少什么?
  • 至少,我认为你可以使用app.Use(new FooMiddleware(next, "/mypath").Invoke);。但我没有在 netcroe 3 上测试过
猜你喜欢
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 2022-11-15
相关资源
最近更新 更多