1+ using System ;
2+ using System . Globalization ;
3+ using System . Linq ;
4+ using Abp ;
5+ using Abp . AspNetCore . Mvc . Controllers ;
6+ using Abp . AspNetCore . Mvc . Extensions ;
7+ using Abp . Auditing ;
8+ using Abp . Extensions ;
9+ using Abp . Timing ;
10+ using Abp . Web . Models ;
11+ using Microsoft . AspNetCore . Http ;
12+ using Microsoft . AspNetCore . Localization ;
13+ using Microsoft . AspNetCore . Mvc ;
14+ using IUrlHelper = Abp . Web . Http . IUrlHelper ;
15+
16+ namespace AbpCompanyName . AbpProjectName . Web . Controllers
17+ {
18+ public class LocalizationController : AbpController
19+ {
20+ private readonly IUrlHelper _urlHelper ;
21+
22+ public LocalizationController ( IUrlHelper urlHelper )
23+ {
24+ _urlHelper = urlHelper ;
25+ }
26+
27+ [ DisableAuditing ]
28+ public virtual ActionResult ChangeCulture ( string cultureName , string returnUrl = "" )
29+ {
30+ if ( ! IsValidCultureCode ( cultureName ) )
31+ {
32+ throw new AbpException ( "Unknown language: " + cultureName + ". It must be a valid culture!" ) ;
33+ }
34+
35+ var cookieValue = CookieRequestCultureProvider . MakeCookieValue (
36+ new RequestCulture ( cultureName , cultureName )
37+ ) ;
38+
39+ Response . Cookies . Append (
40+ CookieRequestCultureProvider . DefaultCookieName ,
41+ cookieValue ,
42+ new CookieOptions
43+ {
44+ Expires = Clock . Now . AddYears ( 2 ) ,
45+ HttpOnly = true
46+ }
47+ ) ;
48+
49+ if ( Request . IsAjaxRequest ( ) )
50+ {
51+ return Json ( new AjaxResponse ( ) ) ;
52+ }
53+
54+ if ( string . IsNullOrWhiteSpace ( returnUrl ) )
55+ {
56+ return LocalRedirect ( "/" ) ;
57+ }
58+
59+ var escapedReturnUrl = Uri . EscapeDataString ( returnUrl ) ;
60+ var localPath = _urlHelper . LocalPathAndQuery ( escapedReturnUrl , Request . Host . Host , Request . Host . Port ) ;
61+ if ( ! string . IsNullOrWhiteSpace ( localPath ) )
62+ {
63+ var unescapedLocalPath = Uri . UnescapeDataString ( localPath ) ;
64+ if ( Url . IsLocalUrl ( unescapedLocalPath ) )
65+ {
66+ return LocalRedirect ( unescapedLocalPath ) ;
67+ }
68+ }
69+
70+ return LocalRedirect ( "/" ) ;
71+ }
72+
73+ private static bool IsValidCultureCode ( string cultureCode )
74+ {
75+ if ( cultureCode . IsNullOrWhiteSpace ( ) )
76+ {
77+ return false ;
78+ }
79+
80+ try
81+ {
82+ return CultureInfo . GetCultures ( CultureTypes . AllCultures )
83+ . Any ( e => e . Name . ToLowerInvariant ( ) == cultureCode . ToLowerInvariant ( ) ) ;
84+ }
85+ catch ( CultureNotFoundException )
86+ {
87+ return false ;
88+ }
89+ }
90+ }
91+ }
0 commit comments