Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Current culture in url when application starts or navigates to home page

I am working on a small web application (Razor Pages) and I have added localization to it. The problem I have now is the following:

When application loads first time or when user presses home button (<a href="/"</a>), the url in the browser is this:

https://localhost/

and when I press a link (<a asp-page="/login"></a>) it navigates me to https://localhost/login instead of https://localhost/{currentCulture}/login

and for this reason, I want to it to be something like this:

https://localhost/{currentCulture}/

For example, for english --> https://localhost/en/

I have already set default current culture and it is applied when application starts but it is not written in the url.

I have followed this tutorial to add localization to my app : http://www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application

Update:

When User presses home button I did this:<a href="/@CultureInfo.CurrentCulture.Name"></a> and it works.

like image 963
ABC Avatar asked Nov 06 '22 22:11

ABC


1 Answers

I do not know how good solution it is, but you can solve this problem so:

Create a class and implement Microsoft.AspNetCore.Rewrite.IRule:

public class FirstLoadRewriteRule : IRule
{
    public void ApplyRule(RewriteContext context)
    {
        var culture = CultureInfo.CurrentCulture;
        var request = context.HttpContext.Request;
        if(request.Path == "/")  
        {
            request.Path = new Microsoft.AspNetCore.Http.PathString($"/{culture.Name}");
        }
    }
}

In your app request.Path == "/" will be true only when app loads first time (when you press home, request.path is "/en" {for English}). So, default culture name will be added to the url. You will not see it in url when app loads, but when you press (<a asp-page="/login"></a>), you will see that you are redirected to https://localhost/en/login.

You have to register this rule in startup.cs in Configure method:

var options = new RewriteOptions().Add(new FirstLoadRewriteRule());
app.UseRewriter(options);
like image 104
BDF Avatar answered Nov 14 '22 23:11

BDF