asp.net mvc - AttributeRouting - Correct way of Getting the Action Name from RouteData -
i have started using attribute routing action methods , struggling in getting action name (and/or id) routedata. below example of how use attrubues so:
[route( "edit/{id:int}" )] public actionresult edit( int id ) { ... }
previously used following method extension of routedata retrieve value
public static string getactionname( routedata routedata ) { return routedata.values[ "action" ] string; }
this used return action name (in example "edit"). alway returns null. inspection of routedata dictionary shows these values seem no longer placed in root of array rather in item keyed "[0] = "ms_directroutematches".
i able access value in following manner due limited understanding of how these values populated concerned that, e.g. routes there more 1 match, code fall on in cases.
public static string getactionname( routedata routedata ) { if( routedata.values.containskey( "ms_directroutematches" ) ) routedata = ( ( ilist<routedata> )routedata.values[ "ms_directroutematches" ] )[ 0 ]; return routedata.values[ "action" ] string; }
what correct way access routedata values populated attributerouting?
your solution work in 1 case. possible request not match route, should ensure action
key exists before return it, or may exception.
public static string getactionname( routedata routedata ) { if( routedata.values.containskey( "ms_directroutematches" ) ) routedata = ( ( ienumerable<routedata> )routedata.values["ms_directroutematches"] )[0]; return routedata.values.containskey("action") ? routedata.values["action"] string : string.empty; }
that 1 case typically passes request iis can return 404 page (or custom 1 if configured), , covers custom 404 page case.
i change ilist
ienumerable
, since adding nothing list in method.
there no such thing request matches more 1 route (0 or 1 route possibilities). in case there no match, ms_directroutematches
not exist. in case exist, there 1 value in collection.
unfortunately, there aren't guarantees number of values in collection won't change more 1 in future version, holds true. since there isn't more robust way determine action name this, stuck until next breaking change.
Comments
Post a Comment