admin管理员组

文章数量:1350324

My first goal is to get the id and code of the language when the user selects a language and keep it in the session. Because I will use the id for database queries and I want to be able to use the language code in the URL.

I am trying to create a dynamic url structure that includes a language code. Actually, I can access what I want, but the language code does not appear in the URL unless I refresh the page.

The URL structure I want:

localhost/en/home/index
localhost/tr/home/index

As I said, I can access this structure right now. But it happens when the user changes or refreshes the page, not on the page where they select the language.

_Layout.cshtml:

<ul class="language-menu">
    @Html.Action("Language", "_Layout")
</ul>

_LayoutController:

[ChildActionOnly]
public PartialViewResult Language()
{
     try
     {
         var languageList = languageService.GetLanguage();
         return base.PartialView("_LanguagePartial", languageList);
     }
     catch (System.Exception)
     {
         throw;
     }
}
public class _LayoutController : BaseController
{
    // SET LANGUAGE
    public ActionResult SetLanguage(int languageID, string languageCode)
    {
        LanguageHelper.SetLanguage(languageID, languageCode);

        string returnUrl = Request.UrlReferrer?.AbsolutePath;

        if (!string.IsNullOrEmpty(returnUrl))
        {
            var newUrl = returnUrl.Replace($"/{LanguageHelper.GetCurrentLanguageCode()}/", $"/{languageCode}/");

            return Redirect(newUrl);
        }

        return RedirectToAction("Index", "Home", new { languageCode });
    }
}

_LanguagePartial.cshtml:

@model List<GAP_Compressor.Models.Language>

@if (Model != null && Model.Any())
{
    foreach (var lang in Model)
    {
        <li>
            <a href="@Url.Action("SetLanguage", "_Layout", new { languageID = lang.language_id, languageCode = lang.code })">
                <img src="@lang.image_path" alt="@lang.code"> @lang.code
            </a>
        </li>
    }
}

LanguageHelper:

public static class LanguageHelper
{
    private const string CurrentLanguageID = "CurrentLanguageID";
    private const string CurrentLanguageCode = "CurrentLanguageCode";

    public static void SetLanguage(int languageID, string languageCode)
    {
        HttpContext.Current.Session[CurrentLanguageID] = languageID;
        HttpContext.Current.Session[CurrentLanguageCode] = languageCode;
    }

    public static int GetCurrentLanguageID()
    {
        return HttpContext.Current.Session[CurrentLanguageID] != null
            ? (int)HttpContext.Current.Session[CurrentLanguageID]
            : 1; 
    }

    public static string GetCurrentLanguageCode()
    {
        return HttpContext.Current.Session[CurrentLanguageCode] != null
            ? HttpContext.Current.Session[CurrentLanguageCode].ToString()
            : "tr"; 
    }
}

RouteConfig:

routes.MapRoute(
     name: "Localized",
     url: "{languageCode}/{controller}/{action}/{id}",
     defaults: new { languageCode = "tr", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

BaseController:

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string currentLanguageCode = LanguageHelper.GetCurrentLanguageCode();

        var cultureInfo = new System.Globalization.CultureInfo(currentLanguageCode);
        System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
        System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;

        var routeData = filterContext.RouteData.Values;

        if (routeData.ContainsKey("languageCode"))
        {
            routeData["languageCode"] = currentLanguageCode; 
        }

        base.OnActionExecuting(filterContext); 
    }
}

本文标签: sessionASPNET MVC Language coded url structureStack Overflow