String URL to RouteValueDictionary - asp.net-mvc

Is there as easy way to convert string URL to RouteValueDictionary collection? Some method like UrlToRouteValueDictionary(string url).
I need such method because I want to 'parse' URL according to my routes settings, modify some route values and using urlHelper.RouteUrl() generate string URL according to modified RouteValueDictionary collection.
Thanks.

Here is a solution that doesn't require mocking:
var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var values = routeData.Values;
// The following should be true for initial version of mvc app.
values["controller"] == "Home"
values["action"] == "Index"
Hope this helps.

You would need to create a mocked HttpContext as routes constrains requires it.
Here is an example that I use to unit test my routes (it was copied from Pro ASP.Net MVC framework):
RouteCollection routeConfig = new RouteCollection();
MvcApplication.RegisterRoutes(routeConfig);
var mockHttpContext = new MockedHttpContext(url);
RouteData routeData = routeConfig.GetRouteData(mockHttpContext.Object);
// routeData.Values is an instance of RouteValueDictionary
//...

I wouldn't rely on RouteTable.Routes.GetRouteData from previous examples because in that case you risk missing some values (for example if your query string parameters don't fully fit any of registered mapping routes). Also, my version doesn't require mocking a bunch of request/response/context objects.
public static RouteValueDictionary UrlToRouteValueDictionary(string url)
{
int queryPos = url.IndexOf('?');
if (queryPos != -1)
{
string queryString = url.Substring(queryPos + 1);
var valuesCollection = HttpUtility.ParseQueryString(queryString);
return new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
}
return new RouteValueDictionary();
}

Here is a solution that doesn't require instantiating a bunch of new classes.
var httpContext = context.Get<System.Web.HttpContextWrapper>("System.Web.HttpContextBase");
var routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(httpContext);
var values = routeData.Values;
var controller = values["controller"];
var action = values["action"];
The owin context contains an environment that includes the HttpContext.

Related

MVC: HtmlHelper: Get action/controller values

My project has a HtmlHelper which generates links (with routeValues) which always direct back to the controller/action which 'spawned' them.
Is it possible to retrieve these values from within the HtmlHelper? i.e without supplying them explicitly. This would work fine....
var url = new UrlHelper(html.ViewContext.RequestContext);
anchorBuilder.MergeAttribute("href", url.Action("Details", routeValues));
...were it not for the fact that that action won't always be "Details".
Or this:
var controller = helper.ViewContext.RouteData.Values["Controller"].ToString();
var action = helper.ViewContext.RouteData.Values["Action"].ToString();
Try this:
var currentAction = html.ViewContext.RouteData.GetRequiredString("action");
var url = new UrlHelper(html.ViewContext.RequestContext);
anchorBuilder.MergeAttribute("href", url.Action(currentAction, routeValues));

Run a URL string through the ASP.NET MVC pipeline to get an ActionResult

I have a list of URLs that I obtained by querying Google Analytics data. I want to run each of these URLs through the MVC pipeline to get the ActionResult. The action result contains the view model from which I can extract some important information.
Based on the extensibility of MVC, I thought this would be easy. I thought I could mock up a HttpRequest using the string URL and pass it through the routing and controller. My end point would be invoking the action method which would return the ActionResult. I'm finding bits and pieces of what I need, but a lot of the methods are protected within the various classes and the documentation on them is pretty sparse.
I somehow want to reach in to the ControllerActionInvoker and get the result of the call to the protected function InvokeActionMethod.
First of all, Darin's answer got me started, but there's a lot more detail to the final solution, so I'm adding a separate answer. This one is complex, so bear with me.
There are 4 steps to getting the ViewResult from a URL:
Mock the RequestContext via the routing system (Darin's answer got me started on this).
Uri uri = new Uri(MyStringUrl);
var request = new HttpRequest(null, uri.Scheme + "://" + uri.Authority + uri.AbsolutePath, string.IsNullOrWhiteSpace(uri.Query) ? null : uri.Query.Substring(1));
var response = new HttpResponse(new StringWriter());
var context = new HttpContext(request, response);
var contextBase = new HttpContextWrapper(context);
var routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(contextBase);
// We shouldn't have to do this, but the way we are mocking the request doesn't seem to pass the querystring data through to the route data.
foreach (string key in request.QueryString.Keys)
{
if (!routeData.Values.ContainsKey(key))
{
routeData.Values.Add(key, request.QueryString[key]);
}
}
var requestContext = new System.Web.Routing.RequestContext(contextBase, routeData);
Subclass your controller. Add a public method that allows you to call the protected Execute(RequestContext) method.
public void MyExecute(System.Web.Routing.RequestContext requestContext)
{
this.Execute(requestContext);
}
In the same subclassed controller, Add a public event that hooks in to the protected OnActionExecuted event. This allows you to reach in a grab the ViewResult via the ActionExecutedContext.
public delegate void MyActionExecutedHandler(ActionExecutedContext filterContext);
public event MyActionExecutedHandler MyActionExecuted;
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (MyActionExecuted != null)
{
MyActionExecuted(filterContext);
}
}
Tie everything together by instantiating an instance of the new controller subclass, adding an event handler, and calling the new public execute method (passing in the mocked RequestContext). The event handler will give you access to the ViewResult.
using (MyCompany.Controllers.MyController c = new Controllers.MyController())
{
c.MyActionExecuted += GrabActionResult;
try
{
c.MyExecute(requestContext);
}
catch (Exception)
{
// Handle an exception.
}
}
and here's the event handler:
private void GrabActionResult(System.Web.Mvc.ActionExecutedContext context)
{
if (context.Result.GetType() == typeof(ViewResult))
{
ViewResult result = context.Result as ViewResult;
}
else if (context.Result.GetType() == typeof(RedirectToRouteResult))
{
// Handle.
}
else if (context.Result.GetType() == typeof(HttpNotFoundResult))
{
// Handle.
}
else
{
// Handle.
}
}
The difficulty here consists into parsing the url into its constituent controller and action. Here's how this could be done:
var url = "http://example.com/Home/Index";
var request = new HttpRequest(null, url, "");
var response = new HttpResponse(new StringWriter.Null);
var context = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
var values = routeData.Values;
var controller = values["controller"];
var action = values["action"];
Now that you know the controller and the action you could use reflection to instantiate and execute it.
Try this:
object result = null;
Type controller = Type.GetType("MvcApplication4.Controllers.HomeController");
if (controller != null)
{
object controllerObj = Activator.CreateInstance(controller, null);
if (controller.GetMethod("ActionName") != null)
{
result = ((ViewResult)controller.GetMethod("ActionName").Invoke(controllerObj, null)).ViewData.Model;
}
}
I assumed normal routes are configured in the application and can be retrieved using regex or string operations. Following your discussion, I learned that you guys want to really follow through the MVC pipeline by digging into the framework by not using reflection or any hardcording techniques. However, I tried to search to minimize hardcoding by trying to match the url with the routes configured in the application by following this thread
How to determine if an arbitrary URL matches a defined route
Also, I came across other thread which creates httprequest to access routedata object but again reflection needs to be used for this.
String URL to RouteValueDictionary
Thanks Ben Mills, this got me started with my own problem. However I found that I didn't have to do 2, 3 or 4, by doing the following.
Uri uri = new Uri(MyStringUrl);
var absoluteUri = uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
var query = string.IsNullOrWhiteSpace(uri.Query) ? null : uri.Query.Substring(1);
var request = new HttpRequest(null, absoluteUri, query);
Getting access to the string writer is important.
var sw = new StringWriter();
var response = new HttpResponse(sw);
var context = new HttpContext(request, response);
var contextBase = new HttpContextWrapper(context);
var routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(contextBase);
If we assign the RouteData to the request context we can use the MVC pipeline as intended.
request.RequestContext.RouteData = routeData;
var controllerName = routeData.GetRequiredString("controller");
var factory = ControllerBuilder.Current.GetControllerFactory();
var contoller = factory.CreateController(request.RequestContext, controllerName);
controller.Execute(request.RequestContext);
var viewResult = sw.ToString(); // this is our view result.
factory.ReleaseController(controller);
sw.Dispose();
I hope this helps someone else wanting to achieve similar things.

How test that ASP.NET MVC route redirects to other site?

Due to a prinitng error in some promotional material I have a site that is receiving a lot of requests which should be for one site arriving at another.
i.e.
The valid sites are http://site1.com/abc & http://site2.com/def but people are being told to go to http://site1.com/def.
I have control over site1 but not site2.
site1 contains logic for checking that the first part of the route is valid in an actionfilter, like this:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
if ((!filterContext.ActionParameters.ContainsKey("id"))
|| (!manager.WhiteLabelExists(filterContext.ActionParameters["id"].ToString())))
{
if (filterContext.ActionParameters["id"].ToString().ToLowerInvariant().Equals("def"))
{
filterContext.HttpContext.Response.Redirect("http://site2.com/def", true);
}
filterContext.Result = new ViewResult { ViewName = "NoWhiteLabel" };
filterContext.HttpContext.Response.Clear();
}
}
I'm not sure how to test the redirection to the other site though.
I already have tests for redirecting to "NoWhiteLabel" using the MvcContrib Test Helpers, but these aren't able to handle (as far as I can see) this situation.
How do I test the redirection to antoher site?
I would recommend you using RedirectResult instead of calling Response.Redirect:
if (youWantToRedirect)
{
filterContext.Result = new RedirectResult("http://site2.com/def")
}
else
{
filterContext.Result = new ViewResult { ViewName = "NoWhiteLabel" };
}
Now if you know how to test ViewResult with MVCContrib TestHelper you will be able to test the RedirectResult the same way. The tricky part is mocking the manager to force it to satisfy the if condition.
UPDATE:
Here's how a sample test might look like:
// arrange
var mock = new MockRepository();
var controller = mock.StrictMock<Controller>();
new TestControllerBuilder().InitializeController(controller);
var sut = new MyFilter();
var aec = new ActionExecutingContext(
controller.ControllerContext,
mock.StrictMock<ActionDescriptor>(),
new Dictionary<string, object>());
// act
sut.OnActionExecuting(aec);
// assert
aec.Result.ShouldBe<RedirectResult>("");
var result = (RedirectResult)aec.Result;
result.Url.ShouldEqual("http://site2.com/def", "");
Update (By Matt Lacey)
Here's how I actually got this working:
// arrange
var mock = new MockRepository();
// Note that in the next line I create an actual instance of my real controller - couldn't get a mock to work correctly
var controller = new HomeController(new Stubs.BlankContextInfoProvider(), new Stubs.BlankWhiteLabelManager());
new TestControllerBuilder().InitializeController(controller);
var sut = new UseBrandedViewModelAttribute(new Stubs.BlankWhiteLabelManager());
var aec = new ActionExecutingContext(
controller.ControllerContext,
mock.StrictMock<ActionDescriptor>(),
// being sure to specify the necessary action parameters
new Dictionary<string, object> { { "id", "def" } });
// act
sut.OnActionExecuting(aec);
// assert
aec.Result.ShouldBe<RedirectResult>("");
var result = (RedirectResult)aec.Result;
result.Url.ShouldEqual("http://site2.com/def", "");

How do i construct a route without ViewContext in ASP.NET MVC?

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)

Url Form Action Without ViewContext

Is it possible to get a URL from an action without knowing ViewContext (e.g., in a controller)? Something like this:
LinkBuilder.BuildUrlFromExpression(ViewContext context, Expression<Action<T>> action)
...but using Controller.RouteData instead of ViewContext. I seem to have metal block on this.
Here's how I do it in a unit test:
private string RouteValueDictionaryToUrl(RouteValueDictionary rvd)
{
var context = MvcMockHelpers.FakeHttpContext("~/");
// _routes is a RouteCollection
var vpd = _routes.GetVirtualPath(
new RequestContext(context, _
routes.GetRouteData(context)), rvd);
return vpd.VirtualPath;
}
Per comments, I'll adapt to a controller:
string path = RouteTable.Routes.GetVirtualPath(
new RequestContext(HttpContext,
RouteTable.Routes.GetRouteData(HttpContext)),
new RouteValueDictionary(
new { controller = "Foo",
action = "Bar" })).VirtualPath;
Replace "Foo" and "Bar" with real names. This is off the top of my head, so I can't guarantee that it's the most efficient solution possible, but it should get you on the right track.
Craig, Thanks for the correct answer. It works great, and it also go me thinking. So in my drive to eliminate those refactor-resistent "magic strings" I have developed a variation on your solution:
public static string GetUrlFor<T>(this HttpContextBase c, Expression<Func<T, object>> action)
where T : Controller
{
return RouteTable.Routes.GetVirtualPath(
new RequestContext(c, RouteTable.Routes.GetRouteData(c)),
GetRouteValuesFor(action)).VirtualPath;
}
public static RouteValueDictionary GetRouteValuesFor<T>(Expression<Func<T, object>> action)
where T : Controller
{
var methodCallExpresion = ((MethodCallExpression) action.Body);
var controllerTypeName = methodCallExpresion.Object.Type.Name;
var routeValues = new RouteValueDictionary(new
{
controller = controllerTypeName.Remove(controllerTypeName.LastIndexOf("Controller")),
action = methodCallExpresion.Method.Name
});
var methodParameters = methodCallExpresion.Method.GetParameters();
for (var i = 0; i < methodParameters.Length; i++)
{
var value = Expression.Lambda(methodCallExpresion.Arguments[i]).Compile().DynamicInvoke();
var name = methodParameters[i].Name;
routeValues.Add(name, value);
}
return routeValues;
}
I know what some will say...dreaded reflection! In my particular application, I think the benefit of maintainability outweighs performance conerns. I welcome any feedback on this idea and the code.

Resources