asp.net mvc. Routing and Url building

前端 未结 2 1086
悲哀的现实
悲哀的现实 2021-02-11 07:20

Does any body knows how to hide some parameters in url?

For example you have a url parameter \"culture\". It can be \"en, fr, it\". By default your site renders in \"en\

2条回答
  •  清酒与你
    2021-02-11 07:56

    This will help:

    ASP.NET mvc, localized routes and the default language for the user

    asp.net mvc localization

    Set Culture in an ASP.Net MVC app

    You have to register two routes:

    routes.MapRoute(
                name: "DefaultLang",
                url: "{language}/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                constraints: new { language = "[a-z]{2}"}
            );
    
    routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    

    Create an Attribute that inherits ActionFilterAttribute:

    public class LanguageActionFilterAttribute : ActionFilterAttribute
        {
    
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                var routeDataKey = "language";
                var defaultLang = "en";
                var defaultCulture = "EN";
    
                // if no language route param received
                if (filterContext.RouteData.Values[routeDataKey] == null /* && currentCulture != "en-EN" */)
                {
                    // change culture to en-EN
                    Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", defaultLang, defaultCulture));
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", defaultLang, defaultCulture));
                }
                else
                {
                     /*if (currentCulture != "whatever")
                     { 
                        //set culture to whatever
                     }*/
                }
    
                base.OnActionExecuting(filterContext);
            }
        }
    

    After that create a BaseController with the previous created attribute:

    [LanguageActionFilter]
    public abstract class BaseController : Controller
    {
    
    }
    

    And all your Controllers will inherit BaseController now, instead of Controller

提交回复
热议问题