title: URL rewrite in OWIN middleware
body: <p>I have a problem with URL rewriting which works in Global.asax but not in OWIN middleware.</p>
  
  <p>Global.asax code</p>
  
  <pre><code>protected void Application_BeginRequest()
  {
      //Perfectly working rewrite. 
      //By route rules, this resolves to the action Global()
      //of the HomeController
      HttpContext.Current.RewritePath("Home/Global");
  }
  </code></pre>
  
  <p>OWIN middleware code (used for culture detection, code shortened for brevity)</p>
  
  <pre><code>public class GlobalizationMiddleware : OwinMiddleware
  {
      public GlobalizationMiddleware(OwinMiddleware next)
          : base(next)
      { }
  
      public async override Task Invoke(IOwinContext context)
      {
          context.Request.Path = new PathString("/Home/Global");
          await Next.Invoke(context);
      }
  }
  </code></pre>
  
  <p>I expect that "Global" action of the controller "Home" gets called...but instead, the default action "Index" is called.</p>
  
  <p>After the Path is changed <code>context.Request.Uri.AbsoluteUri</code> is <code><a href="http://localhost/Global/Home" rel="noreferrer">http://localhost/Global/Home</a></code></p>
  
  <p>But Controller's <code>Request.Url.AbsoluteUri</code> is still <code><a href="http://localhost" rel="noreferrer">http://localhost</a></code></p>
  
  <p>I even tried <code>context.Environment["owin.RequestPath"] = "/Home/Global";</code> but that doesn's seem to work either.</p>
  
  <p>Before anyone asks, yes, I call the <code>IAppBuilder.Use(typeof(GlobalizationMiddleware))</code> in Startup.cs and the debugger enters the Invoke method.</p>
  
  <p>What am I doing wrong?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I even tried referencing <code>System.Web</code> and then doing this...doesn't work either :(</p>
  
  <pre><code>System.Web.Routing.RequestContext requestContext = context.Environment["System.Web.Routing.RequestContext"] as System.Web.Routing.RequestContext;
  requestContext.HttpContext.RewritePath("/Home/Global");
  
  System.Web.HttpContextBase contextBase = context.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextBase;
  contextBase.RewritePath("/Home/Global");
  </code></pre>
  
  <p><strong>EDIT 2 - Found a working solution (see below) but I'm unsure whether it's the right solution, comments would be appreciated :)</strong></p>