2016-05-23 26 views
1

我試圖使用中間件重定向301舊版URL。ASP.NET Core RC1 MVC 6 - 如何從中間件訪問UrlHelper並創建Url到Action

private static Boolean IsLegacyPathToPost(this HttpContext context) 
{ 
    return context.IsLegacyPath() && context.Request.Path.Value.Contains("/archives/"); 
} 

public static void HandleLegacyRoutingMiddleware(this IApplicationBuilder builder) 
{ 
    builder.MapWhen(context => context.IsLegacyPathToPost(), RedirectFromPost); 
} 

private static void RedirectFromPost(IApplicationBuilder builder) 
{ 
    builder.Run(async context => 
    { 
     await Task.Run(() => 
     { 
      //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); 
     }); 
    }); 
} 

正如你可以看到,我使用的方法MapWhen,限制我的實例化方法RedirectFromPost裏面我IUrlHelper實例。 ServiceProvider給了我一個空實例,沒有正確使用IUrlHelper.Action()所需的ActionContext。

有沒有人遇到過類似的挑戰,對我有幫助?

回答

2

反射之後,由於中間件在MVC之前執行,所以無法創建ActionContext,因爲它根本不存在。

所以正確的方法是,如果你真的想使用UrlHelper.Action來創建你的URL,使用傳統的url模式來創建一個ActionFilter或者一個專門的Action。

相關問題