ASP.NET MVC - Routing and ActionFilterAttribute

本文关键字:and ActionFilterAttribute Routing NET MVC ASP | 更新日期: 2023-09-27 17:52:33

我使用以下路由来满足我的文化要求:

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

我也有下面的过滤器:

public class CultureFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        var cultureName = (filterContext.RouteData.Values["culture"] as string) ?? string.Empty;
        if (!string.IsNullOrWhiteSpace(cultureName) && CultureHelper.IsValidCulture(cultureName))
        {
            // e.g if requested cultureName is EN-ZZ the below method will get EN-US
            cultureName = CultureHelper.GetImplementedCulture(cultureName);
            filterContext.RouteData.Values["culture"] = cultureName;
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
        }
    }
}

因此,正如您在ActionFilterAttribute上看到的那样,我根据请求的url获得了近似的文化。

一切都很好,但我想改变url也在上述场景中,用户请求的EN-ZZ,我得到EN-US。

有可能吗?

Thanks to lot

ASP.NET MVC - Routing and ActionFilterAttribute

如果您不需要更改浏览器url,请尝试:

var cultureName = (filterContext.RouteData.Values["culture"] as string) ?? string.Empty;
if (string.Compare(cultureName,"EN-ZZ",true) == 0)
{
    cultureName  = "EN-US";
}

如果你需要改变浏览器的url,你需要重定向用户:

var cultureName = (filterContext.RouteData.Values["culture"] as string) ?? string.Empty;
if (string.Compare(cultureName, "EN-ZZ", true) == 0)
{
     filterContext.RouteData.Values["culture"] = "EN-US"; //Replace with another culture
     filterContext.Result = new RedirectToRouteResult(filterContext.RouteData.Values);
}
else if (!string.IsNullOrWhiteSpace(cultureName) && CultureHelper.IsValidCulture(cultureName))
{
        // e.g if requested cultureName is EN-ZZ the below method will get EN-US
        cultureName = CultureHelper.GetImplementedCulture(cultureName);
        filterContext.RouteData.Values["culture"] = cultureName;
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
 }