refactor add culture midleware
This commit is contained in:
46
EnvelopeGenerator.Web/Middleware/CultureMiddleware.cs
Normal file
46
EnvelopeGenerator.Web/Middleware/CultureMiddleware.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using EnvelopeGenerator.Web.Models;
|
||||
using Microsoft.AspNetCore.Localization;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Globalization;
|
||||
|
||||
namespace EnvelopeGenerator.Web.Middleware;
|
||||
|
||||
public class CultureMiddleware
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
private readonly Cultures _cultures;
|
||||
|
||||
public CultureMiddleware(RequestDelegate next, IOptions<Cultures> culturesOpt)
|
||||
{
|
||||
_next = next;
|
||||
_cultures = culturesOpt.Value;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var cookieName = CookieRequestCultureProvider.DefaultCookieName;
|
||||
var cookieValue = context.Request.Cookies[cookieName];
|
||||
|
||||
if (string.IsNullOrEmpty(cookieValue))
|
||||
{
|
||||
var culture = new RequestCulture(_cultures.Default.Language);
|
||||
|
||||
var cookieOptions = new CookieOptions
|
||||
{
|
||||
Secure = false,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
HttpOnly = true
|
||||
};
|
||||
|
||||
context.Response.Cookies.Append(
|
||||
cookieName,
|
||||
CookieRequestCultureProvider.MakeCookieValue(culture),
|
||||
cookieOptions);
|
||||
|
||||
CultureInfo.CurrentCulture = new CultureInfo(_cultures.Default.Language);
|
||||
CultureInfo.CurrentUICulture = new CultureInfo(_cultures.Default.Language);
|
||||
}
|
||||
|
||||
await _next(context);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user