Home > front end >  Culture is not provided in the anchor tag
Culture is not provided in the anchor tag

Time:08-01

I'm currently building a Razor web application in .NET6 who have 3 cultures.

The problem is all my anchor tags are empty in the DOM, when I click on the Contact link, it doesn't do anything.

<a  asp-area="" asp-page="/Contact">Contact</a>

Here is my Program.cs

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddRazorPages()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddFolderRouteModelConvention("/", model =>
        {
            foreach (var selector in model.Selectors)
            {
                selector.AttributeRouteModel.Template = AttributeRouteModel.CombineTemplates("{culture?}", selector.AttributeRouteModel.Template);
            }
        });
    });
builder.Services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();
builder.Services.Configure<RequestLocalizationOptions>(opt =>
{
    var supportedCultures = new List<CultureInfo>
    {
        new CultureInfo("en"),
        new CultureInfo("fr"),
        new CultureInfo("nl")
    };
    opt.DefaultRequestCulture = new RequestCulture("en");
    opt.SupportedCultures = supportedCultures;
    opt.SupportedUICultures = supportedCultures;
    opt.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider()
    {
        RouteDataStringKey = "culture",
        UIRouteDataStringKey = "culture",
        Options = opt
    });
});

builder.Services.AddHttpContextAccessor();

builder.Services.AddLocalization(opt => { opt.ResourcesPath = "Resources"; });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

var options = ((IApplicationBuilder)app).ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

//app.UseRequestLocalization(((IApplicationBuilder)app).ApplicationServices.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);

app.MapRazorPages();

app.Run();

When I manually browse to www.website.com/fr/contact-us then it works, but then when I click on the below anchor (Home), my url change to www.website.com/fr/contact-us/Index

<a asp-area="" asp-page="/">Home</a>

What am I missing?

CodePudding user response:

Add the culture param to the route for all links:

<a asp-area="" 
   asp-page="/" 
   asp-route-culture="@CultureInfo.CurrentCulture.Name">Home</a>

Another way:

@{
    var cltr = System.Globalization.CultureInfo.CurrentCulture.Name;
}

<a href="@Url.Page("Index", new { area="", culture=cltr })">Home</a>
  • Related