Dynamic ASP MVC URLs

I am trying to create a very simple application that allows my client to create their own pages. The hard part is letting them create their own URL.

The client must fill out:

  • The name of the page (for example, about us).
  • Description of the page (for example, we are a big company).
  • URL of the page (e.g. / About)

When a customer enters this information and saves it, it must be stored in a database.

I can easily create a controller called "Page" that takes the value "ID", and when the user enters "www.someurl.com/Page/1", a pop-up page appears.

But I really want the user to write "www.someurl.com/About" and then the page pops up.

How can this be done using some kind of dynamic rewrite / route code using ASP MVC.

+3
source share
5 answers

My idea would be to create a field in your "Page" table called "Slug". When your user creates a new page, they will have to fill in the "Slug" field and enter what they would like to see in the URL (for example: the page wanted - "About", slug - "about" | page wanted - "See Our sponsors, slug - see-our-sponsors, etc.). You can automate this process with a bit of javascript if you want.

Create a route like this:

routes.MapRoute(
    null,
    {slug},
    new { controller = "Page", action = "ChoosePage" });

Create this mode of action:

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult ChoosePage(string slug)
{
    //Logic to display page
}

, URL-, , "slug" .

+7

, , , , . ​​ .

, "" . , . , , , "" , , .

, "Site". : URI, URI. , ActionLink RouteLink, , , , . , , , .

+7

, , - " ".

.

1- (, // id).
2- /, (: admin)
3- . db , . , 404 , .

+3

, , !

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Home",
            "",
            new { controller = "Home", action = "Index" }
        );

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

        routes.MapRoute(
            "Page",
            "{*slug}",
            new { controller = "Page", action = "ChoosePage" }
        );

    }
+2

:

1. RouteTable

RouteTable.Routes.Insert(1,new Route("Test", new RouteValueDictionary(new { controller = "Page", action = "ChoosePage" ,pagename="Test" }), new MvcRouteHandler()));

public ActionResult ChoosePage(string pagename)
{
    return View(pagename);
}

, .

  1. Global.asax.cs Application_Start()
+2
source

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


All Articles