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。
有沒有人遇到過類似的挑戰,對我有幫助?