开发者

ASP.NET MVC - Wordpress Style URLs

开发者 https://www.devze.com 2023-01-04 00:51 出处:网络
Wordpress is very highly regarded and proven to follow good practise which in turn facilitates rankings with search engines.

Wordpress is very highly regarded and proven to follow good practise which in turn facilitates rankings with search engines.

One proven factor is the seo freindly urls. Such as the examples below;

www.myblog.com/test
www.myblog.com/another
www.myblog.com/contact

Lets say that we have two controllers, each with their won actions;

View/BlogPost
View/BlogCategory
Contact/Form
Contact/Post

The wordpress view engine is flexible enough that the test url can resolve to BlogPost and the another url can resolve to BlogCategory.

Does anyone know if this is possible in MVC and is it feasible? Im thinking about a custom 4开发者_开发知识库04 handler that would preserve the url in the browser and then fire the required actions.


You define a route in the global.asax like this, the bottom one being the default:

        routes.MapRoute(
            "Test",
            "test",
            new { controller = "View", action = "BlogPost"}
        );

        routes.MapRoute(
            "Another",
            "another",
            new { controller = "View", action = "BlogCategory"}
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

The second parameter in MapRoute() is the URL, in your case "test" and "another". You can probably see here, that you can store this route data somewhere else, like a db, then foreach through them adding each one to the RouteCollection.


You could add an Action to your controller, with a RedirectToAction() call

...
public ActionResult test()
{
    return RedirectToAction("BlogPost");
}
..
public ActionResult another()
{
    return RedirectToAction("BlogCategory");
}
...


As other guys answered above it's easy to have such routes to have friendly "Slug" URLs. There are also some tricks to build pretty clean URLs like WordPress. I have written two blog posts on this topic which may help you have a better understanding of Slug URLs: Build pretty clean URL for your dynamic pages using JavaScript and Translating your content title using Google Translate API to use in a URL

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号