How do i have optional parameter but still validate them in asp.net mvc routing?
I have this route that i just added
routes.MapRoute(
"MyRoute",
"MyController/{action}/{orgId}/{startDate}/{endDate}",
new
{
controller = "MyController",
action = "MyAction",
orgId = 0,
startDate = DateTime.Today.AddMonths(-1),
endDate = DateTime.Today
},
new
{
action = new FromValuesListConstraint(new string[] { "MyAction", "MyActionEx" }),
orgId = new IntegerRouteConstraint(),
startDate = new DateTimeRouteConstraint(),
endDate = new DateTimeRouteConstraint()
}
when i put in this url, it resolves down to the default route (controller, action,id) and the above rout does not catch this url:
http://localhost:1713/MyController/MyAction/16
But this below works fine.
http://localhost:1713/MyController/My开发者_JAVA技巧Action/16/11-May-10/11-May-10
my question is that i thought both would work as i am giving default values to the startDate and enddate fields
i tested this using the RouteDebugger and this route turned up false
how can i have these last two parameter as optional but still have the validation ?
The problem is this in this current format does not fit to your route (requires 5-part URL). You may change this line
startDate = DateTime.Today.AddMonths(-1),
endDate = DateTime.Today
to
startDate = UrlParameter.Optional,
endDate = UrlParameter.Optional
And do the conversion and defaults in the controller itself.
You could follow @Aliostad's method and then write your own action filter attribute to validate the parameters that are coming into the method. If they don't validate against your constraints then reject the url as you would normally.
public class ValidateParameterFilter : ActionFilterAttribute
{
base.OnActionExecuting(filterContext);
bool areParametersValid = true;
if (filterContext.ActionParameters.ContainsKey("startDate"))
{
DateTime startDate;
if (!DateTime.TryParse(filterContext.ActionParameters["startDate"].ToString(), out startDate))
{
// Not a DateTime so bad data in here
areParametersValid = false;
}
}
if (filterContext.ActionParameters.ContainsKey("endDate"))
{
DateTime endDate;
if (!DateTime.TryParse(filterContext.ActionParameters["endDate"].ToString(), out endDate))
{
// Not a DateTime so bad data in here
areParametersValid = false;
}
}
if (!areParametersValid)
{
// Redirect to error page or throw an exception
}
}
Then on your action just decorate it with the attribute
[ValidateParameterFilter]
public ActionResult MyAction (int orgId, DateTime startDate, DateTime endDate)
{
...
}
Although I thought if you had the type declared as DateTime then an abc value would get rejected.
精彩评论