i've got an action method like the following
public JsonResult Index(string version)
{
.. do stuff, return some data v1 or v2. Default = v2.
}
So, this action method returns some data, which can be formatted either as Version 1
or Version 2
(whatever output that is ... just know that they are schemantically different).
So, when a user wants to call access this resource, they the following :
http://www.blah.com/api/Index
nothing too hard.
they can also do this...
http://www.blah.com/api/Index?version=1.0
BUT, is it possible to make it so that the user can use the query string params version
or v
eg. http://www.blah.com/api/Index?v=1.0
and this will populate the version parameter in the ActionMethod. Possible?
I'm guessing you could manipulate the action method parameter(s) using an action filter.
Basically just check for a 'v' in the QueryString
collection, and if it exists, throw it into the ActionParameters
collection.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var version = filterContext.HttpContext.Request.QueryString["v"];
if (!string.IsNullOrEmpty(version))
filterContext.ActionParameters["version"] = version;
}
HTHs,
Charles
EDIT: Making it a bit more generic...
public class QueryStringToActionParamAttribute : ActionFilterAttribute
{
private string _queryStringName;
private string _actionParamName;
public QueryStringToActionParamAttribute(string queryStringName, string actionParamName)
{
_queryStringName = queryStringName;
_actionParamName = actionParamName;
}
public override void OnActionExecuting(ActionExecutedContext filterContext)
{
var queryStringValue = filterContext.HttpContext.Request.QueryString[_queryStringName];
if (!string.IsNullOrEmpty(queryStringValue))
{
filterContext.ActionParameters[_actionParamName] = queryStringValue;
}
}
}
Then you could call it like:
[QueryStringToActionParam("v", "version")];