开发者

Issue with MVC route conflicts

开发者 https://www.devze.com 2023-03-23 08:45 出处:网络
I have a multilingual MVC application which among other things has some simple \"CMS\" pages which are handled by a page controller. The route which I\'ve defined is:

I have a multilingual MVC application which among other things has some simple "CMS" pages which are handled by a page controller. The route which I've defined is:

routes.MapRoute(
    "Page",
    "Page/{name}",
    new { controller = "Page", action = "Index", name = "" }
);

Also I have a method defined in a "base controller" which is used to change the language of the current page.

public ActionResult ChangeCulture(Culture lang, string returnUrl)
{
    if (returnUrl.Length >= 3)
    {
        returnUrl = returnUrl.Substring(3);
    }

    return Redirect("/" + lang.ToString() + returnUrl);
}

For example, for the "About Us" page in English, the Spanish version is available via the following URL: http://localhost/en/Page/ChangeCulture?lang=2&returnUrl=/es/Page/AboutUs

The problem is that this URL maps to the route that I've defined for the CMS pages which obv开发者_开发技巧iously does not exist. Is there a way I can ignore the URL "Page/ChangeCulture" so it maps to the correct method i.e. the one defined in the "base controller"?

Thanks,

Jose


You can try setting route constraint on name parameter.

routes.MapRoute(
                "Page",
                "Page/{name}",
                new { controller = "Page", action = "Index", name = "" },
                new { name = new PageNameConstraint() }
                );


You should re-architect your URLs. Why is the spanish version of the About Us page be served in different URLs? In your example:

  1. http://localhost/en/Page/ChangeCulture?lang=2&returnUrl=/es/Page/AboutUs
  2. http://localhost/es/Page/AboutUs

Make every page work in every language with a consistent URL (in this example, the second one). Your routing would then look like:

    routes.MapRoute(
    "Page",
    "{lang}/Page/{name}",
    new { controller = "Page", lang = "en", action = "Index", name = "" }
);

and you can even call RedirectToaction instead of Redirect and use more robust form of constructing the URL. e.g. :

RedirectToAction("Index", new { page = "AboutUS", lang = "es" } );
0

精彩评论

暂无评论...
验证码 换一张
取 消