将路由映射到中间件类? [英] Map a route to a middleware class?

查看:86
本文介绍了将路由映射到中间件类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来这应该是一个直截了当的问题,但是我一直无法通过Google找到解决方案.

Seems like this should be a straightforward question, but I've been unable to find a solution via Google.

在ASP.NET Core中,将 IHttpHandler 实现器替换为中间件类似乎是非常标准的.旧系统的优点是您可以设置HTTP处理程序以响应在web.config中指定的路由.

It seems pretty standard that in ASP.NET Core, IHttpHandler implementors are replaced by middleware classes. One nicety of the old system was that you could set up an HTTP handler to respond to a route, specified in the web.config.

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

So, for instance, if my IHttpHandler implementor was named FooHandler, web.config would contain something like:

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

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

Is there a one-to-one replacement for routing like this in ASP.NET Core? How do I do this?

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

Edit: The new middleware class might look something like:

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>();
        }
    }
}

推荐答案

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

You can use Map extension method of IApplicationBuilder like that :

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

您也可以在中间件中完成

You can also do it inside your Middleware

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
    }
}

这篇关于将路由映射到中间件类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆