forked from grandnode/grandnode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericPathRoute.cs
220 lines (196 loc) · 10.7 KB
/
GenericPathRoute.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using Grand.Core;
using Grand.Core.Data;
using Grand.Core.Domain.Localization;
using Grand.Core.Infrastructure;
using Grand.Framework.Localization;
using Grand.Services.Seo;
using MediatR;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Grand.Framework.Seo
{
/// <summary>
/// Provides properties and methods for defining a SEO friendly route, and for getting information about the route.
/// </summary>
public class GenericPathRoute : LocalizedRoute
{
#region Fields
private readonly IRouter _target;
#endregion
#region Ctor
public GenericPathRoute(IRouter target, string routeName, string routeTemplate, RouteValueDictionary defaults,
IDictionary<string, object> constraints, RouteValueDictionary dataTokens, IInlineConstraintResolver inlineConstraintResolver)
: base(target, routeName, routeTemplate, defaults, constraints, dataTokens, inlineConstraintResolver)
{
_target = target ?? throw new ArgumentNullException(nameof(target));
}
#endregion
#region Utilities
/// <summary>
/// Get route values for current route
/// </summary>
/// <param name="context">Route context</param>
/// <returns>Route values</returns>
protected async Task<RouteValueDictionary> GetRouteValues(RouteContext context)
{
var path = context.HttpContext.Request.Path.Value;
if (SeoFriendlyUrlsForPathEnabled(context.HttpContext) && !SeoFriendlyUrlsForLanguagesEnabled(context.HttpContext))
{
string lastpath = path.Split('/').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault();
path = $"/{lastpath}";
}
//remove language code from the path if it's localized URL
if (SeoFriendlyUrlsForLanguagesEnabled(context.HttpContext))
{
await PrepareLanguages(context.HttpContext);
if (path.IsLocalizedUrl(context.HttpContext.Request.PathBase, false, await LanguagesAsync(context.HttpContext), out Language language))
path = path.RemoveLanguageSeoCodeFromUrl(context.HttpContext.Request.PathBase, false);
}
//parse route data
var routeValues = new RouteValueDictionary(this.ParsedTemplate.Parameters
.Where(parameter => parameter.DefaultValue != null)
.ToDictionary(parameter => parameter.Name, parameter => parameter.DefaultValue));
var matcher = new TemplateMatcher(this.ParsedTemplate, routeValues);
matcher.TryMatch(path, routeValues);
return routeValues;
}
#endregion
#region Methods
/// <summary>
/// Route request to the particular action
/// </summary>
/// <param name="context">A route context object</param>
/// <returns>Task of the routing</returns>
public override async Task RouteAsync(RouteContext context)
{
if (!DataSettingsHelper.DatabaseIsInstalled())
return;
//try to get slug from the route data
var routeValues = await GetRouteValues(context);
if (!routeValues.TryGetValue("GenericSeName", out object slugValue) || string.IsNullOrEmpty(slugValue as string))
return;
var slug = slugValue as string;
//virtual directory path
var pathBase = context.HttpContext.Request.PathBase;
//performance optimization, we load a cached verion here. It reduces number of SQL requests for each page load
var urlRecordService = context.HttpContext.RequestServices.GetRequiredService<IUrlRecordService>();
var urlRecord = await urlRecordService.GetBySlugCached(slug);
//no URL record found
if (urlRecord == null)
return;
//if URL record is not active let's find the latest one
if (!urlRecord.IsActive)
{
var activeSlug = await urlRecordService.GetActiveSlug(urlRecord.EntityId, urlRecord.EntityName, urlRecord.LanguageId);
if (string.IsNullOrEmpty(activeSlug))
return;
//redirect to active slug if found
var redirectionRouteData = new RouteData(context.RouteData);
redirectionRouteData.Values["controller"] = "Common";
redirectionRouteData.Values["action"] = "InternalRedirect";
redirectionRouteData.Values["url"] = $"{pathBase}/{activeSlug}{context.HttpContext.Request.QueryString}";
redirectionRouteData.Values["permanentRedirect"] = true;
context.HttpContext.Items["grand.RedirectFromGenericPathRoute"] = true;
context.RouteData = redirectionRouteData;
await _target.RouteAsync(context);
return;
}
//ensure that the slug is the same for the current language,
//otherwise it can cause some issues when customers choose a new language but a slug stays the same
var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
var slugForCurrentLanguage = await SeoExtensions.GetSeName(urlRecordService, context.HttpContext, urlRecord.EntityId, urlRecord.EntityName, workContext.WorkingLanguage.Id);
if (!string.IsNullOrEmpty(slugForCurrentLanguage) && !slugForCurrentLanguage.Equals(slug, StringComparison.OrdinalIgnoreCase))
{
//we should make validation above because some entities does not have SeName for standard (Id = 0) language (e.g. news, blog posts)
//redirect to the page for current language
var redirectionRouteData = new RouteData(context.RouteData);
redirectionRouteData.Values["controller"] = "Common";
redirectionRouteData.Values["action"] = "InternalRedirect";
redirectionRouteData.Values["url"] = $"{pathBase}/{slugForCurrentLanguage}{context.HttpContext.Request.QueryString}";
redirectionRouteData.Values["permanentRedirect"] = false;
context.HttpContext.Items["grand.RedirectFromGenericPathRoute"] = true;
context.RouteData = redirectionRouteData;
await _target.RouteAsync(context);
return;
}
//since we are here, all is ok with the slug, so process URL
var currentRouteData = new RouteData(context.RouteData);
switch (urlRecord.EntityName.ToLowerInvariant())
{
case "product":
currentRouteData.Values["controller"] = "Product";
currentRouteData.Values["action"] = "ProductDetails";
currentRouteData.Values["productid"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "category":
currentRouteData.Values["controller"] = "Catalog";
currentRouteData.Values["action"] = "Category";
currentRouteData.Values["categoryid"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "manufacturer":
currentRouteData.Values["controller"] = "Catalog";
currentRouteData.Values["action"] = "Manufacturer";
currentRouteData.Values["manufacturerid"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "vendor":
currentRouteData.Values["controller"] = "Catalog";
currentRouteData.Values["action"] = "Vendor";
currentRouteData.Values["vendorid"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "newsitem":
currentRouteData.Values["controller"] = "News";
currentRouteData.Values["action"] = "NewsItem";
currentRouteData.Values["newsItemId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "blogpost":
currentRouteData.Values["controller"] = "Blog";
currentRouteData.Values["action"] = "BlogPost";
currentRouteData.Values["blogPostId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "topic":
currentRouteData.Values["controller"] = "Topic";
currentRouteData.Values["action"] = "TopicDetails";
currentRouteData.Values["topicId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "knowledgebasearticle":
currentRouteData.Values["controller"] = "Knowledgebase";
currentRouteData.Values["action"] = "KnowledgebaseArticle";
currentRouteData.Values["articleId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "knowledgebasecategory":
currentRouteData.Values["controller"] = "Knowledgebase";
currentRouteData.Values["action"] = "ArticlesByCategory";
currentRouteData.Values["categoryId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
case "course":
currentRouteData.Values["controller"] = "Course";
currentRouteData.Values["action"] = "Details";
currentRouteData.Values["courseId"] = urlRecord.EntityId;
currentRouteData.Values["SeName"] = urlRecord.Slug;
break;
default:
//no record found, thus generate an event this way developers could insert their own types
await context.HttpContext.RequestServices.GetRequiredService<IMediator>().Publish(new CustomUrlRecordEntityNameRequested(currentRouteData, urlRecord));
break;
}
context.RouteData = currentRouteData;
//route request
await _target.RouteAsync(context);
}
#endregion
}
}