gehgassi_backend/gehGassi.Web/Helper/RouteValueRequestCultureProvider.cs

63 lines
2.6 KiB
C#

using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
namespace gehGassi.Web.Helper
{
/// <summary>
/// Hilfsklasse die das Routing basierend auf Cultures implementiert und die gewählte Sprache setzt
/// </summary>
public class RouteValueRequestCultureProvider : RequestCultureProvider
{
/// <inheritdoc />
public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
string cultureCode = null;
if (httpContext.Request.Path.HasValue && httpContext.Request.Path.Value == "/")
cultureCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName; //this.GetDefaultCultureCode();
else if (httpContext.Request.Path.HasValue && httpContext.Request.Path.Value.Length >= 4 && httpContext.Request.Path.Value[0] == '/' && httpContext.Request.Path.Value[3] == '/')
{
cultureCode = httpContext.Request.Path.Value.Substring(1, 2);
if (!this.CheckCultureCode(cultureCode))
cultureCode = this.GetDefaultCultureCode(); //throw new HttpException(HttpStatusCode.NotFound);
}
else if (httpContext.Request.Path.HasValue && httpContext.Request.Path.Value.Length == 3 && httpContext.Request.Path.Value[0] == '/')
{
cultureCode = httpContext.Request.Path.Value.Substring(1, 2);
if (!this.CheckCultureCode(cultureCode))
cultureCode = this.GetDefaultCultureCode(); //throw new HttpException(HttpStatusCode.NotFound);
}
else cultureCode = this.GetDefaultCultureCode(); //throw new HttpException(HttpStatusCode.NotFound);
ProviderCultureResult requestCulture = new ProviderCultureResult(cultureCode);
return Task.FromResult(requestCulture);
}
/// <summary>
/// Standard-Culture holen
/// </summary>
/// <returns>Standard-Culture</returns>
private string GetDefaultCultureCode()
{
return this.Options.DefaultRequestCulture.Culture.TwoLetterISOLanguageName;
}
/// <summary>
/// Prüft ob die gewählte Culture unterstützt wird
/// </summary>
/// <param name="cultureCode">Culture</param>
/// <returns>true wenn unterstützt, false sonst</returns>
private bool CheckCultureCode(string cultureCode)
{
return this.Options.SupportedCultures.Select(c => c.TwoLetterISOLanguageName).Contains(cultureCode);
}
}
}