如何将所有动作重定向到一个动作 [英] How to redirect all actions to one action
问题描述
我想将控制器下的所有操作重定向到其索引操作
(该控制器中的一个,其他控制器将保持默认行为)
i want to re-direct all actions under a controller to its index action (one that controller, other controllers will remain default behavior)
例如对于控制器 O
http://foo.com/o/abc
http://foo.com/o
http://foo.com/o/abc?foo=bar
以上所有请求都将转到索引操作
all the above request will all go to "index" action
我尝试使用以下路由设置,但是当我尝试访问 http://foo.com/o/abc 。
I tried to use below route setting, but ASP.NET complain 404 when i try to visit "http://foo.com/o/abc".
routes.MapRoute(
name: "ORoute",
url: "o/*",
defaults: new { controller = "O", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
谢谢
推荐答案
首先,使用显示自定义无效地址页面的一个动作定义一个名为错误的控制器。
First , define a controller named Error with One Action which show Customized Invalid Address page ..
然后,您需要定义一个继承DefaultControllerFactory $ b的类。 $ b(它的名字是CF)
Then you need to define a Class with inherit DefaultControllerFactory ( it's name is CF)
然后您应该重写其Main方法:CreateController
and Then you should override its Main Method : CreateController
,将此语句添加到global.asax中,这意味着任何请求都应由此类验证。
and finally , add this statement to global.asax which means any request should be verified by this Class.
CF类代码:
public class CF : DefaultControllerFactory
{
public override IController CreateController(RequestContext requestContext, string controllerName)
{
IController result;
try
{
result = base.CreateController(requestContext, controllerName);
}
catch (Exception)
{
result = base.CreateController(requestContext, "Error");
}
return result;
}
}
Global.asax:
Global.asax :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
// Here is the Change
ControllerBuilder.Current.SetControllerFactory(typeof(CF));
}
这篇关于如何将所有动作重定向到一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!