0

I want to display of post content with like below url.
http://domainname.com/name-of-post

Please help me to solved this problem with route config.

This is my codes :

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

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

        routes.MapRoute(
            name: "ShortUrl",
            url: "{PostName}",
            defaults: new { controller = "ShortUrl", action = "Post", PostName = UrlParameter.Optional }
            );
    }



    public ActionResult shortaddress(string _postName = "post-name")
    {

        return RedirectToRoute("ShortUrl", new { postName = _postName });
    }

    [Route(Name = "ShortUrl")]
    public ActionResult Post(string postName)
    {
        if (string.IsNullOrEmpty(postName))
            return RedirectToAction("Index", "Home");

        var postData = postsInfo.getPost(postName);


        return View(postData);
    }
Hossein
  • 3,083
  • 3
  • 16
  • 33
  • Solve which part ? generating short url part or setting up the routing so that `yourSite/shortUrl` will render the post ? – Shyju Sep 26 '18 at 01:20
  • 1
    First, your `Default` route matches any url containing between 0 and 4 segments, therefore your `ShortUrl` will never be hit. Second, only the last parameter can be marked `UrlParameter.Optional` so you need to remove `param = UrlParameter.Optional`. Third, your `[Route(Name = "ShortUrl")]` does nothing since you have not enabled attribute routing. –  Sep 26 '18 at 06:23
  • Last, in order for `ShortUrl` to work, it needs to be first, and it needs a constraint - refer [Routing in ASP.NET MVC, showing username in URL](https://stackoverflow.com/questions/37358416/routing-in-asp-net-mvc-showing-username-in-url/37359345#37359345). However that will affect performance, so I suggest you change the route definition to include a prefix to uniquely identify it, for example `url: "Post/{PostName}"` (and again locate it before the `Default` route –  Sep 26 '18 at 06:26

0 Answers0