title: ASP.NET Core RC1 MVC 6 - How to access UrlHelper From Middleware and create Url to Action
body: <p>I'm trying to redirect 301 a legacy URL using a middleware.</p>
  
  <pre><code>private static Boolean IsLegacyPathToPost(this HttpContext context)
  {
      return context.IsLegacyPath() &amp;&amp; context.Request.Path.Value.Contains("/archives/");
  }
  
  public static void HandleLegacyRoutingMiddleware(this IApplicationBuilder builder)
  {
      builder.MapWhen(context =&gt; context.IsLegacyPathToPost(), RedirectFromPost);
  }
  
  private static void RedirectFromPost(IApplicationBuilder builder)
  {
      builder.Run(async context =&gt;
      {
          await Task.Run(() =&gt;
          {
              //urlHelper is instanciated but it's ActionContext is null
              IUrlHelper urlHelper = context.RequestServices.GetService(typeof(IUrlHelper)) as IUrlHelper;
  
              IBlogContext blogContext = context.RequestServices.GetService(typeof(IBlogContext)) as IBlogContext;
              //Extract key
              var sections = context.Request.Path.Value.Split('/').ToList();
              var archives = sections.IndexOf("archives");
              var postEscapedTitle = sections[archives + 1];
              //Query categoryCode from postEscapedTitle
              var query = new GetPostsQuery(blogContext).ByEscapedTitle(postEscapedTitle).WithCategory().Build();
              var categoryCode = query.Single().Categories.First().Code;
              //Redirect
              context.Response.Redirect(urlHelper.Action("Index", "Posts", new { postEscapedTitle = postEscapedTitle, categoryCode = categoryCode }), true);
          });
      });
  }
  </code></pre>
  
  <p>As you can read, I'm using the MapWhen method, which restrict me instanciate my IUrlHelper instance inside the RedirectFromPost method.
  The ServiceProvider give me an empty instance, without the ActionContext needed to properly use IUrlHelper.Action().</p>
  
  <p>Did anyone met a similar challenge and have insight for me ?</p>