Dynamically modify RouteValueDictionary

◇◆丶佛笑我妖孽 提交于 2019-11-28 11:37:58

If I do understand correctly what is the question:

So, is there a way I can overwrite the RouteValueDictionary for this request? Or is there some other way I can do this that I'm missing?

I've taken your solution and changed these lines to replace parameter names:

for (int i = 0; i < methodParameters.Length; i++)
{
    // I. instead of this

    //values.First(x => x.Key == unMappedList.ElementAt(i).Key)
    //    .Key = methodParameters.ElementAt(i).Name; 
    //above doesn't work, but even if it did it wouldn't do the right thing

    // II. do this (not so elegant but working;)
    var key = unMappedList.ElementAt(i).Key;
    var value = values[key];
    values.Remove(key);
    values.Add(methodParameters.ElementAt(i).Name, value);

    // III. THIS is essential! if statement must be moved after the for loop
    //return true;
}
return true; // here we can return true

NOTE: I like your approach. Sometimes it is simply much more important to extend/adjust routing then go to code and "fix incorrect parameter names". And of course, they are most likely NOT incorrect.

And here is the power of Separation of concern.

  • Url addresses are one place.
  • Controller, action and parameter names other one.
  • And Routing with powerful customization...

...as the only correct place where to handle that. This is separation of concern. Not tweaking the action names to serve Url...

Jamie Ide

You can easily restrict the parameters to positive integers with a regular expression:

private const string IdRouteConstraint = @"^\d+$";

routes.MapRoute(
   name: "Default2",
   url: "{controller}/{action}/{param1}-{param2}",
   defaults: new { controller = "Admin", action = "Index" },
   constraints: new { param1 = IdRouteConstraint, param2 = IdRouteConstraint});

As I said in my answer to your earlier question, you shouldn't worry about the parameter names in the controller actions. Giving those overly meaningful names will tie you in knots.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!