ASP.NET MVC - hiding identifier in URL?

I am creating a basic blog application just now, to view the data I just use the default route, i.e. -

routes.MapRoute
(
     "Default", // Route name
     "{controller}/{action}/{id}",
     new { controller = "Blog", action = "Index", id = UrlParameter.Optional } 
);

So, when you go to mysite.com/View/12, it displays a blog with id 12. I want to change the urls to look like this: mysite.com/View/2010/06/01/this -is- The-headline.

I could have a URL mapping like -

        routes.MapRoute(
            "View",
            "View/{year}/{month}/{day}/{title}",
            new { controller = "Blog", action = "View" }
        );

Controller, , . , , URL-, , . URL-, , , URL-?

!

+3
4

Title , , URL-, . , ( ).

, , ,

/2010/05/31/23343-the-topic-has-the-id-in-it

+2

URL- . // ( , URL, ). , , ( ). , db .

, "slug", URL .

, (, "blog/{slug *}" ), URL-, , , blog/2010/02/05/my-title actionmethod , "2010/02/05/my-title"

+1

- , URL- URL-. , URL- , .

public ActionResult Index(int id)
{
    BlogPost blogPost=blogRepository.GetPost(id);
    TempData["post"]=blogPost;
    //this makes sure post is stored in memory so it doesn't get to database again
    return Redirect("/View/"+blogPost.year+"/"+blogPost.month+"/"+blogPost.day+"/"+blogPost.title);
}

public ActionResult View(int year, int month, int day, string title)
{
    if(TempData["post]"==null)//I assume you will publish links with that URL, so someone can be routed here without redirecting
    {

        BlogPost blogPost=blogRepository.GetPost(title);
        return View(blogPost);
    }
    else 
        return View(TempData["post"]);
}

, , , . , ID, Redirect TempData .

0
source

When the identifier is passed, I set the session variable and then redirect the user to another ActionResult controller that reads the session variable. This is annoying hacking, but also annoying the display of the identifier in the url. The SessionVariables class, which you see below, is just a class of static properties that get / set session variables.

The end result is a redirect to a view without an identifier using session variables.

public ActionResult ViewContext(Int64 ContextID)
    {

        SessionVariables.the_context = "UserView";
        SessionVariables.the_context_id = ContextID;

        return RedirectToAction("ViewWithNoID");
    }

    public ActionResult ViewWithNoID()
    {
        //Change this to UserView

        Security_User obj = Security_User.getByPK(SessionVariables.the_context_id);

        return View("View", obj);
    }
0
source

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


All Articles