是否可以在运行时动态指定动作名称?
问题描述:
string actionName = "Users";
[HttpGet]
[ActionName(actionName)]
public ActionResult GetMe()
{
}
...给出了:一个对象引用需要非静态字段,方法或属性是否可以在运行时动态指定动作名称?
这只是一个测试,虽然,有没有办法做到这一点?如果是这样,我可以重新使用相同的控制器,并可能在运行中创建新的URI ...对吗?
答
假设你有如下控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
你可以写一个自定义的路由处理:
public class MyRouteHander : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var rd = requestContext.RouteData;
var action = rd.GetRequiredString("action");
var controller = rd.GetRequiredString("controller");
if (string.Equals(action, "users", StringComparison.OrdinalIgnoreCase) &&
string.Equals(controller, "home", StringComparison.OrdinalIgnoreCase))
{
// The action name is dynamic
string actionName = "Index";
requestContext.RouteData.Values["action"] = actionName;
}
return new MvcHandler(requestContext);
}
}
最后,在你的路由定义的自定义路由处理程序相关联:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MyRouteHander();
现在如果您要求/home/users
这是将被提供的Home
控制器的10个动作。
答
您可以在另一个路由参数中执行switch语句。
如果我做了一个switch语句并不意味着我需要事先知道这些URI吗? – BigOmega 2011-06-15 18:23:52
还不完全。您有控制器手动处理路由。 – 2011-06-15 18:40:16