-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathUrlRewritingStep.cs
89 lines (69 loc) · 2.55 KB
/
UrlRewritingStep.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
using System.Text.Json.Nodes;
using Microsoft.Extensions.Localization;
using OrchardCore.Recipes.Models;
using OrchardCore.Recipes.Services;
using OrchardCore.UrlRewriting.Models;
namespace OrchardCore.UrlRewriting.Recipes;
/// <summary>
/// This recipe step creates or updates a set of URL rewrite rule.
/// </summary>
public sealed class UrlRewritingStep : NamedRecipeStepHandler
{
private readonly IRewriteRulesManager _rewriteRulesManager;
internal readonly IStringLocalizer S;
public UrlRewritingStep(
IRewriteRulesManager rewriteRulesManager,
IStringLocalizer<UrlRewritingStep> stringLocalizer)
: base("UrlRewriting")
{
_rewriteRulesManager = rewriteRulesManager;
S = stringLocalizer;
}
protected override async Task HandleAsync(RecipeExecutionContext context)
{
var model = context.Step.ToObject<UrlRewritingStepModel>();
var tokens = model.Rules.Cast<JsonObject>() ?? [];
foreach (var token in tokens)
{
RewriteRule rule = null;
var id = token[nameof(RewriteRule.Id)]?.GetValue<string>();
if (!string.IsNullOrEmpty(id))
{
rule = await _rewriteRulesManager.FindByIdAsync(id);
if (rule != null)
{
await _rewriteRulesManager.UpdateAsync(rule, token);
}
}
if (rule == null)
{
var sourceName = token[nameof(RewriteRule.Source)]?.GetValue<string>();
if (string.IsNullOrEmpty(sourceName))
{
context.Errors.Add(S["Could not find rule source value. The rule will not be imported"]);
continue;
}
rule = await _rewriteRulesManager.NewAsync(sourceName, token);
if (rule == null)
{
context.Errors.Add(S["Unable to find a rule-source that can handle the source '{Source}'.", sourceName]);
continue;
}
}
var validationResult = await _rewriteRulesManager.ValidateAsync(rule);
if (!validationResult.Succeeded)
{
foreach (var error in validationResult.Errors)
{
context.Errors.Add(error.ErrorMessage);
}
continue;
}
await _rewriteRulesManager.SaveAsync(rule);
}
}
}
public sealed class UrlRewritingStepModel
{
public JsonArray Rules { get; set; }
}