i have complex asp.net mvc routing scenario , want able parse url pull 'referrer' request header using existing routes.
i have incoming requests this:
http://hostname/{scope}/{controller}/{action}
with corresponding route mapping:
routes.maproute( name: "scoped", url: "{scope}/{controller}/{action}/{id}", defaults: new { controller = "equipment", action = "index", id = urlparameter.optional, scope = "shared" } );
in onactionexecuting
method of base class of controllers pull resulting scope
routedata:
var scope= (filtercontext.routedata.values["scope"] string).tolower();
i use scope construct filters database queries. worked fine until moved json-returning methods separate set of webapi2 controllers. have route:
config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{action}" );
all ajax requests made api controllers, means not have scope
value available. want solve using 'referrer' url request header, is url include scope
.
what when apicontroller initializes:
public void pullcurrentscopedomainfromrequestheader(system.net.http.headers.httprequestheaders headers) { var refererurl = headers.getvalues("referer").first(); //do magic scope }
the difficulty scope can have default value ("shared"), in case url "http://hostname/controller/action" get's passed in. best (and dryest) way scope url, somehow using "scoped" route mapped in routing config parse url somehow. have no idea how that. can help?
you need build fake http context based on url , use static routetable
parse url routevaluedictionary
.
// create fake httpcontext using url var uri = new uri("http://hostname/controller/action", urikind.absolute); var request = new httprequest( filename: string.empty, url: uri.tostring(), querystring: string.isnullorempty(uri.query) ? string.empty : uri.query.substring(1)); // create textwriter null stream backing stream // doesn't consume resources using (var nullwriter = new streamwriter(stream.null)) { var response = new httpresponse(nullwriter); var httpcontext = new httpcontext(request, response); var fakehttpcontext = new httpcontextwrapper(httpcontext); // use routetable parse url routedata var routedata = routetable.routes.getroutedata(fakehttpcontext); var values = routedata.values; // values dictionary contains keys , values // url. // key | value // // controller | controller // action | action // id | {} }
note can use specific route routetable
specifying name.
var routedata = routetable.routes["scoped"].getroutedata(fakehttpcontext);
Comments
Post a Comment