且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC2父控制器不重定向

更新时间:2023-11-17 12:09:16

我不认为这是应该做你想要的正确方法。相反,你应该使用在你的路由的路由约束,以确保该ID的存在,和下降从那里回来一网打尽的路子。

I don't think that's the proper way to do what you want. Instead you should use route constraints on your routes to make sure the id exists, and fall back from there in a "catch all" route.

事情是这样的:

Routes.MapRoute("Name", "Url", new { ... }, new {
    Id = new IdConstraint() // <- the constraint returns true/false which tells the route if it should proceed to the action
});

的约束将是这样的:

The constraint would be something like this:

public class IdConstraint : IRouteConstraint {
    public bool Match(
        HttpContextBase Context,
        Route Route,
        string Parameter,
        RouteValueDictionary Dictionary,
        RouteDirection Direction) {
        try {
            int Param = Convert.ToInt32(Dictionary[Parameter]);

            using (DataContext dc = new DataContext() {
                ObjectTrackingEnabled = false
            }) {
                return (dc.Table.Any(
                    t =>
                        (t.Id == Param)));
            };
        } catch (Exception) {
            return (false);
        };
    }
}

这是我和我的路由使用,以确保我收到确实存在的ID。如果它不存在,则该约束返回一个假的,并且路由不执行与该请求继续向下的路线连锁。在你的路由的最底部,你应该有一个通用的捕捉,发送你的用户的页面,告诉他们,他们想不存在,做X或X(沿着这些线路的东西什么都的路线,我只是来了与场景)。

This is what I use with my routes to make sure that I'm getting an Id that really exists. If it doesn't exist, the constraint returns a false, and the route does not execute and the request continues down the route chain. At the very bottom of your routes you should have a generic catch all route that sends your user to a page that tells them what they want doesn't exist and to do X or X (something along those lines, I'm just coming up with scenarios).