Rewrite or change routing in asp.net MVC url?

I want to be able to rewrite my url to one level of url. This means that I need to make a dynamic (change in each language) rewrite rule, for example:

Source Address: http://www.mydomain.com/account/pages/13

I always want to show the url at the same level:

http://www.mydomain.com/my-page-title

there will never be more than one slash / after a domain name.

I also need to be able to translate the page title in the above example:

http://www.mydomain.com/my-translated-page

How can I achieve this, and it should be able to change this at runtime - that is, "improve" the URL, as well as rewrite the rules in htaccess

+4
source share
3 answers

You need to create your own Routes. When you use MVC4, set this custom route above the default application route.

 routes.MapRoute(
      name: "Custom_Route",
      url: "My-Page-Title/{id}",
      defaults: new { controller = "Home", action = "About", id = UrlParameter.Optional }
 );

And for translating urls into mvc

+3
source

. . , . , MVC Routing /controller/action/id, Id s, , .

, , , URL, . !

. , -- .

public static string SeoName(string name)
{
    return Regex.Replace(name.ToLower().Replace(@"'", String.Empty), @"[^\w]+", "-");
}

, Interface . . .

, , .

+1

, ,

routes.MapRoute(
                name: "Default_Custom",
                url: "MyCustom-{action}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

, Global.asax

protected void Application_Start()
{
  RouteConfig.RegisterRoutes(RouteTable.Routes);
}

woks , @Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })

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

Source: https://habr.com/ru/post/1532216/


All Articles