ASP.NET MVC2使用通配符或自由文本URL自定义路由

时间:2010-09-28 02:03:30

标签: c# asp.net-mvc-2 routing url-rewriting httpmodule

我要求在asp.net mvc2网站上添加特定功能,以提供附加的SEO功能,如下所示:

传入的URL是纯文本,可能包含如下句子

“http://somesite.com/welcome-to-our-web-site”或 “http://somesite.com/cool things / check-out-this-awesome-video”

在MVC管道中,我想获取此URL,剥离网站名称,查找数据库表中的剩余部分,并根据表中数据的内容调用适当的控制器/视图。所有控制器只需从查找表中获取一个唯一的id。可以在不同的URL上使用不同的控制器,但必须从数据库中删除它。

如果无法解析网址,则需要提供404错误,如果找到但过时的网址,则需要提供302重定向。

如果网址已解析,则必须将其保留在浏览器地址栏中。

我已经看过路由模型和自定义路由,并且无法完全解决如何使用这些,因为基于简单的路由不会预定义控制器。我也不确定如何提供404,302回到标题。 Perhpas我需要一个自定义的httpmodule或类似的东西,但是那里的东西超出了我的理解。

这必须以某种方式可行......我们几年前在Classic ASP中做过。任何人都可以帮忙解决一些如何实现这个目标的细节吗?

1 个答案:

答案 0 :(得分:1)

嗯,最简单的方法是在网址的某个地方设置一个id(通常是第一个选项)

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

在你的控制器中,你会有像

这样的东西
public class HomeController {
    public ActionResult Index(int id) {
        //check database for id
        if(id_exists) {
            return new RedirectResult("whereever you want to redirect", true);
        } else {
            return new HttpNotFoundResult();
        }
    }
}

如果您不想使用id方法,您可以执行其他操作,例如......

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

public ActionResult Index(string category, string page_name) {
    //same as before but instead of looking for id look for pagename
}

后者的问题是你需要考虑所有类型的路线,如果你有很多与各种类型相匹配的参数,它会变得非常困难。

这应该让你朝着正确的方向前进。如果你需要一些澄清,请告诉我,我会看看我是否可以写一条特定的路线来帮助你

其他

你可以做你正在寻找的事情

public ActionResult Index() {
    //Create and instance of the new controlle ryou want to handle this request
    SomeController controller = new SomeController();
    controller.ControllerContext = this.ControllerContext;
    return controller.YourControllerAction();
}

但我不知道这样做会产生任何副作用......所以这可能不是一个好主意 - 但它似乎有效。