I want to create a route from a utility class that doesn't have access to a ViewContext.
Is this possible? There doesnt seem to be any equivalent of ViewContext.Current
I've tried fishing around in all the constructors for Routing and HttpContext but can't quite get to what I want.
This is what I'm looking for - although this doesn't work because RouteTable.Routes
is of type RouteCollection
and not RouteData
. So close - yet so far :-)
RequestContext requestContext = new RequestContext(HttpContext.Current, RouteTable.Routes);
UrlHelper url = new UrlHelper(requestContext);
var urlString = url.RouteUrl(new {controller="DynamicImage", action="Button", text="Hello World"});
Note: RequestContest is of type System.Web.Routing.RequestContext and not HttpContext
Try this:
var httpContext = new HttpContextWrapper(HttpContext.Current);
var requestContext = new RequestContext(httpContext);
var urlHelper = new UrlHelper(requestContext, new RouteData()));
Hope this helps
UPDATED:
The previous is not correct (I've posted it from my memory). Try this instead (it works in one of my projects):
var httpContext = new HttpContextWrapper(HttpContext.Current);
var requestContext = new RequestContext(httpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext);
new RouteData()
is using just only for RequestContext
initialization and new UrlHelper(requestContext)
actually calls new UrlHelper(requestContext, RouteTable.Routes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With