Is it possible to specify Action names dynamically at run time?
string actionName = "Users";
开发者_如何学编程
[HttpGet]
[ActionName(actionName)]
public ActionResult GetMe()
{
}
...gives: An object reference is required for the non-static field, method, or property
That was just a test though, is there a way to do this? If so, I could re-use the same Controller and possibly create new URIs on the fly... right?
Assuming you have the following controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
you could write a custom route handler:
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);
}
}
Finally associate the custom route handler in your route definitions:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MyRouteHander();
Now if you request /home/users
it's the Index
action of the Home
controller that will be served.
You can just take another routing argument in and do a switch statement.
精彩评论