-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
BaseController.cs
313 lines (268 loc) · 11.7 KB
/
BaseController.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;
using Microsoft.Extensions.Primitives;
using Nop.Core;
using Nop.Core.Events;
using Nop.Core.Http.Extensions;
using Nop.Core.Infrastructure;
using Nop.Services.Localization;
using Nop.Web.Framework.Events;
using Nop.Web.Framework.Models;
using Nop.Web.Framework.Mvc.Filters;
using Nop.Web.Framework.UI;
namespace Nop.Web.Framework.Controllers;
/// <summary>
/// Base controller
/// </summary>
[HttpsRequirement]
[PublishModelEvents]
[SignOutFromExternalAuthentication]
[ValidatePassword]
[SaveIpAddress]
[SaveLastActivity]
[SaveLastVisitedPage]
[ForceMultiFactorAuthentication]
public abstract partial class BaseController : Controller
{
#region Rendering
/// <summary>
/// Render component to string
/// </summary>
/// <param name="componentType">Component type</param>
/// <param name="arguments">Arguments</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the result
/// </returns>
protected virtual async Task<string> RenderViewComponentToStringAsync(Type componentType, object arguments = null)
{
var helper = new DefaultViewComponentHelper(
EngineContext.Current.Resolve<IViewComponentDescriptorCollectionProvider>(),
HtmlEncoder.Default,
EngineContext.Current.Resolve<IViewComponentSelector>(),
EngineContext.Current.Resolve<IViewComponentInvokerFactory>(),
EngineContext.Current.Resolve<IViewBufferScope>());
using var writer = new StringWriter();
var context = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());
helper.Contextualize(context);
var result = await helper.InvokeAsync(componentType, arguments);
result.WriteTo(writer, HtmlEncoder.Default);
await writer.FlushAsync();
return writer.ToString();
}
/// <summary>
/// Render partial view to string
/// </summary>
/// <param name="viewName">View name</param>
/// <param name="model">Model</param>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the result
/// </returns>
protected virtual async Task<string> RenderPartialViewToStringAsync(string viewName, object model)
{
//get Razor view engine
var razorViewEngine = EngineContext.Current.Resolve<IRazorViewEngine>();
//create action context
var actionContext = new ActionContext(HttpContext, RouteData, ControllerContext.ActionDescriptor, ModelState);
//set view name as action name in case if not passed
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.ActionDescriptor.ActionName;
//partial view are not part of the controller life cycle.
//hence, we could no use action filters to intercept the Models being returned
//as we do in the /Nop.Web.Framework/Mvc/Filters/PublishModelEventsAttribute.cs for controllers
switch (model)
{
case BaseNopModel nopModel:
{
var eventPublisher = EngineContext.Current.Resolve<IEventPublisher>();
//we publish the ModelPrepared event for all models as the BaseNopModel,
//so you need to implement IConsumer<ModelPrepared<BaseNopModel>> interface to handle this event
eventPublisher.ModelPreparedAsync(nopModel).Wait();
break;
}
case IEnumerable<BaseNopModel> modelCollection:
{
var eventPublisher = EngineContext.Current.Resolve<IEventPublisher>();
//we publish the ModelPrepared event for collection as the IEnumerable<BaseNopModel>,
//so you need to implement IConsumer<ModelPrepared<IEnumerable<BaseNopModel>>> interface to handle this event
eventPublisher.ModelPreparedAsync(modelCollection).Wait();
break;
}
}
//set model
ViewData.Model = model;
//try to get a view by the name
var viewResult = razorViewEngine.FindView(actionContext, viewName, false);
if (viewResult.View == null)
{
//or try to get a view by the path
viewResult = razorViewEngine.GetView(null, viewName, false);
if (viewResult.View == null)
throw new ArgumentNullException($"{viewName} view was not found");
}
await using var stringWriter = new StringWriter();
var viewContext = new ViewContext(actionContext, viewResult.View, ViewData, TempData, stringWriter, new HtmlHelperOptions());
await viewResult.View.RenderAsync(viewContext);
return stringWriter.GetStringBuilder().ToString();
}
#endregion
#region Notifications
/// <summary>
/// Error's JSON data
/// </summary>
/// <param name="error">Error text</param>
/// <returns>Error's JSON data</returns>
protected JsonResult ErrorJson(string error)
{
return Json(new
{
error
});
}
/// <summary>
/// Error's JSON data
/// </summary>
/// <param name="errors">Error messages</param>
/// <returns>Error's JSON data</returns>
protected JsonResult ErrorJson(object errors)
{
return Json(new
{
error = errors
});
}
/// <summary>
/// Display "Edit" (manage) link (in public store)
/// </summary>
/// <param name="editPageUrl">Edit page URL</param>
protected virtual void DisplayEditLink(string editPageUrl)
{
var nopHtmlHelper = EngineContext.Current.Resolve<INopHtmlHelper>();
nopHtmlHelper.AddEditPageUrl(editPageUrl);
}
#endregion
#region Localization
/// <summary>
/// Add locales for localizable entities
/// </summary>
/// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>
/// <param name="languageService">Language service</param>
/// <param name="locales">Locales</param>
protected virtual async Task AddLocalesAsync<TLocalizedModelLocal>(ILanguageService languageService,
IList<TLocalizedModelLocal> locales) where TLocalizedModelLocal : ILocalizedLocaleModel
{
await AddLocalesAsync(languageService, locales, null);
}
/// <summary>
/// Add locales for localizable entities
/// </summary>
/// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>
/// <param name="languageService">Language service</param>
/// <param name="locales">Locales</param>
/// <param name="configure">Configure action</param>
protected virtual async Task AddLocalesAsync<TLocalizedModelLocal>(ILanguageService languageService,
IList<TLocalizedModelLocal> locales, Action<TLocalizedModelLocal, int> configure) where TLocalizedModelLocal : ILocalizedLocaleModel
{
foreach (var language in await languageService.GetAllLanguagesAsync(true))
{
var locale = Activator.CreateInstance<TLocalizedModelLocal>();
locale.LanguageId = language.Id;
configure?.Invoke(locale, locale.LanguageId);
locales.Add(locale);
}
}
#endregion
#region Security
/// <summary>
/// Access denied view
/// </summary>
/// <returns>Access denied view</returns>
protected virtual IActionResult AccessDeniedView()
{
var webHelper = EngineContext.Current.Resolve<IWebHelper>();
//return Challenge();
return RedirectToAction("AccessDenied", "Security", new { pageUrl = webHelper.GetRawUrl(Request) });
}
/// <summary>
/// Access denied JSON data for DataTables
/// </summary>
/// <returns>
/// A task that represents the asynchronous operation
/// The task result contains the access denied JSON data
/// </returns>
protected virtual async Task<JsonResult> AccessDeniedDataTablesJson()
{
var localizationService = EngineContext.Current.Resolve<ILocalizationService>();
return ErrorJson(await localizationService.GetResourceAsync("Admin.AccessDenied.Description"));
}
#endregion
#region Cards and tabs
/// <summary>
/// Save selected card name
/// </summary>
/// <param name="cardName">Card name to save</param>
/// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request. Pass null to ignore</param>
public virtual void SaveSelectedCardName(string cardName, bool persistForTheNextRequest = true)
{
//keep this method synchronized with
//"GetSelectedCardName" method of \Nop.Web.Framework\Extensions\HtmlExtensions.cs
ArgumentException.ThrowIfNullOrEmpty(cardName);
const string dataKey = "nop.selected-card-name";
if (persistForTheNextRequest)
{
TempData[dataKey] = cardName;
}
else
{
ViewData[dataKey] = cardName;
}
}
/// <summary>
/// Save selected tab name
/// </summary>
/// <param name="tabName">Tab name to save; empty to automatically detect it</param>
/// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request. Pass null to ignore</param>
public virtual async Task SaveSelectedTabNameAsync(string tabName = "", bool persistForTheNextRequest = true)
{
//default root tab
SaveSelectedTabName(tabName, await Request.GetFormValueAsync("selected-tab-name"), null, persistForTheNextRequest);
//child tabs (usually used for localization)
//Form is available for POST only
if (!Request.IsPostRequest() || !Request.HasFormContentType)
return;
var form = await Request.ReadFormAsync();
foreach (var item in form)
if (item.Key.StartsWith("selected-tab-name-", StringComparison.InvariantCultureIgnoreCase))
SaveSelectedTabName(null, item.Value, item.Key["selected-tab-name-".Length..], persistForTheNextRequest);
}
/// <summary>
/// Save selected tab name
/// </summary>
/// <param name="tabName">Tab name to save; empty to automatically detect it</param>
/// <param name="persistForTheNextRequest">A value indicating whether a message should be persisted for the next request. Pass null to ignore</param>
/// <param name="selectedTabName">Selected tab name</param>
/// <param name="dataKeyPrefix">A prefix for child tab to process</param>
protected virtual void SaveSelectedTabName(string tabName, StringValues selectedTabName, string dataKeyPrefix, bool persistForTheNextRequest)
{
//keep this method synchronized with
//"GetSelectedTabName" method of \Nop.Web.Framework\Extensions\HtmlExtensions.cs
if (string.IsNullOrEmpty(tabName))
tabName = selectedTabName;
if (string.IsNullOrEmpty(tabName))
return;
var dataKey = "nop.selected-tab-name";
if (!string.IsNullOrEmpty(dataKeyPrefix))
dataKey += $"-{dataKeyPrefix}";
if (persistForTheNextRequest)
TempData[dataKey] = tabName;
else
ViewData[dataKey] = tabName;
}
#endregion
}