将路由映射到中间件类?

时间:2017-12-14 23:28:31

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

似乎这应该是一个简单的问题,但我一直无法通过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>();
        }
    }
}

1 个答案:

答案 0 :(得分: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
    }
}