mvc.net routing: routevalues in maproutes

2020-08-01 05:18发布

I need urls like /controller/verb/noun/id and my action methods would be verb+noun. For example I want /home/edit/team/3 to hit the action method

public ActionResult editteam(int id){}

I have following route in my global.asax file.

routes.MapRoute(
              "test",
              "{controller}.mvc/{verb}/{noun}/{id}",
              new { docid = "", action = "{verb}"+"{noun}", id = "" }


            );

URLs correctly match the route but I don't know where should I construct the action parameter that is name of action method being called.

2条回答
可以哭但决不认输i
2楼-- · 2020-08-01 05:31

Try:

public class VerbNounRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        IRouteHandler handler = new MvcRouteHandler();
        var vals = requestContext.RouteData.Values;
        vals["action"] = (string)vals["verb"] + vals["noun"];
        return handler.GetHttpHandler(requestContext);
    }
}

I don't know of a way to hook it for all routes automatically, but in your case you can do it for that entry like:

routes.MapRoute(
   "test",
   "{controller}.mvc/{verb}/{noun}/{id}",
   new { docid = "", id = "" }
   ).RouteHandler = new VerbNounRouteHandler();
查看更多
\"骚年 ilove
3楼-- · 2020-08-01 05:51

Try the following, use this as your route:

routes.MapRoute(
              "HomeVerbNounRoute",
              "{controller}/{verb}/{noun}/{id}",
              new { controller = "Home", action = "{verb}"+"{noun}", id = UrlParameter.Optional }
            );

Then you simply put your actionresult method:

public ActionResult editteam(int id){}

Into Controllers/HomeController.cs and that will get called when a URL matches the provided route.

查看更多
登录 后发表回答