Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created July 15, 2015 11:32
Show Gist options
  • Save chilversc/96e774d4cbc9fb2f6dc2 to your computer and use it in GitHub Desktop.
Save chilversc/96e774d4cbc9fb2f6dc2 to your computer and use it in GitHub Desktop.
ASP.Net MVC - Choose method to handle action based upon query string parameters

The scenario is a some external legacy code is accessing the site. In the past the request was handled by an IHttpHandler that dispatched to different private methods to handle the request based upon query string parameters.

The goal is to replace the IHttpHandler with a standard MVC controller.

  • The different requests should go to different methods.
  • We want to retain the standard MVC parameter binding.
  • We do not want one action with lots of parameters, many of which are unrelated.
public class TestController : Controller
{
// No selector, this acts as the fallback if none of the other methods match
public ActionResult Index ()
{
return Content ("Index");
}
// Alias this method to the Index action as all the requests come in to the same action.
// The OtherAttribute will be used to check if the query string contains "other=true".
[Other, ActionName ("Index")]
public ActionResult Other ()
{
return Content ("Other");
}
private class OtherAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
var qs = controllerContext.HttpContext.Request.QueryString;
var value = qs.Get("OTHER");
return string.Equals(bool.TrueString, value, StringComparison.OrdinalIgnoreCase);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment