I have the following custom middleware that sets the current culture info.
At the end, I want to redirect to another page, but my code isn't working.
In use, it seems like the execution stop's after invoking my middleware.
It currently uses context.Response.Redirect(redir);.
Middleware, SetCulture.cs:
public class SetCulture
{
private readonly RequestDelegate _next;
public SetCulture(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IAssetsConfigAccessor config)
{
string name = string.Empty;
if (context.Request.Query.Count > 0 && context.Request.Query.ContainsKey("culture"))
{
context.Session.SetString("Culture", context.Request.Query["culture"]);
name = context.Request.Query["culture"];
}
else if (context.Session.Keys.Contains("Culture"))
{
name = context.Session.GetString("Culture");
}
else if (context.Request.Cookies.ContainsKey("Culture"))
{
name = context.Request.Cookies["Culture"];
}
else
{
ISite site = await config.GetSiteAsync();
if (site.Cultures.Count() > 0)
{
ISiteCulture siteCult = site.Cultures.SingleOrDefault(c => c.IsDefault);
if (!siteCult.Null())
{
name = siteCult.Culture.Name;
}
else
{
name = Thread.CurrentThread.CurrentCulture.Name;
}
context.Session.SetString(AssetsStatics.CacheCurrentCultureName, name);
}
else
{
ICulture tmp = await config.GetCultureAsync(false);
name = tmp.Name;
}
}
CultureInfo cult = new CultureInfo(name);
CultureInfo.CurrentCulture = cult;
CultureInfo.CurrentUICulture = cult;
string redir = context.Request.Query.ContainsKey("returnUrl") ? context.Request.Query["returnUrl"] : "/";
context.Response.Redirect(redir);
await _next.Invoke(context);
}
}
How I configure it in Program.cs:
app
.UseWhen(cntx => cntx.Request.Path.StartsWithSegments("/Assets/SetCulture")
&& cntx.Request.Query.ContainsKey("Culture"),
bld => { bld.UseMiddleware<SetCulture>(); });
UseWhenis acceptable too. Now I see another problem: SettingCultureInfo.CurrentCulture+ 1 doesn't work as you intend. You're setting the culture of the thread that is about to redirect the user. This is not setting the culture of the "future request product of the redirect".return;after redirecting. The.Redirect()method sets a redirect result object that the output formatter translates to an HTTP redirect response. If you call _next(), other middleware might return other responses that invalidate your redirect.