如何在ASP.NET MVC中制作简短的URL以显示帖子内容

时间:2018-09-25 20:52:01

标签: asp.net-mvc

我要显示具有类似于url以下的帖子内容
    http://domainname.com/name-of-post

请帮助我使用route config解决此问题。

这是我的代码:

    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);
    }

0 个答案:

没有答案