HttpContext.Current.RewritePath 在 ASP.NET 5 中的什么位置?

Where to place HttpContext.Current.RewritePath in ASP.NET 5?

我在 asp.net 做开发。最近我发现 asp.net 5 中没有 Global.asax 文件。

要放入 Global.asax 文件的其中一件事是 URL 重写。

Global.asax 文件不见了。我可以在哪里放置 URL 重写代码。我的意思是我在 ASP.NET 4.0

中做了类似的事情
 HttpContext.Current.RewritePath(...);

我不想使用URL重写模块。我只想用 HttpContext.Current.RewritePath 方法来做。

我的问题是我可以把上面的代码放在什么地方 ASP.NET 5?

这里需要 OWIN 中间件。因为它是 vNext 中 HttpModules 的替代品。

Startup.cs文件

的Configure方法中写入以下代码
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<MyMiddleware>();
    }
}

您的定制中间件可能如下所示:

public class MyMiddleware
{
    private readonly RequestDelegate _test;

    public MyMiddleware(RequestDelegate test)
    {
        _test = test;
    }

    public async Task Invoke(HttpContext context)
    {   
        return _test.Invoke(context);
    }
}

在 Startup 的 Configure 方法的开头创建并添加一个新的中间件(您希望它在任何其他中间件之前执行)。示例 here

如下实现调用方法来做一个url重写

public Task Invoke(HttpContext context)
{
    // modify url
    context.Request.Path = new PathString(context.Request.Path.Value + 'whatever');
    // continue
    return _next(context);
}

我在 Github 上分析 aspnet/StaticFiles 回购协议时遇到了这个问题。

作为显式创建中间件 class 的替代方法,也可以使用 IApplicationBuilder.Use

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //...built-in initialization...

    app.Use(requestDelegate =>
    {
        return new RequestDelegate(context =>
        {
            // modify url (from mbudnik's answer)
            context.Request.Path = new PathString(context.Request.Path.Value + 'whatever');

            // continue with the pipeline
            return requestDelegate(context);
        });
    });
}

在这种情况下,中间件直接指定为 Func<RequestDelegate, RequestDelegate> 的实例,而不是自定义 classes。