【问题标题】:Where to place HttpContext.Current.RewritePath in ASP.NET 5?在 ASP.NET 5 中放置 HttpContext.Current.RewritePath 的位置?
【发布时间】:2015-12-02 18:51:41
【问题描述】:

我在 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 中间件是 ASP.NET vNext 中 HttpModules 的替代品。
  • 是的,正如我所说,它是 Startup.cs!
  • global.asax中有Application_BeginRequest之类的事件吗?

标签: c# asp.net .net url-rewriting asp.net-core


【解决方案1】:

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

如下实现invoke方法进行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 repo 时遇到了这个问题。

【讨论】:

    【解决方案2】:

    作为显式创建中间件类的替代方法,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> 的实例,而不是自定义类。

    【讨论】:

      【解决方案3】:

      您需要 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);
          }
      }
      

      【讨论】:

      • 我会怎么做url rewriting
      猜你喜欢
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多