How to generate url in global.asax using my route. int asp.net mvc
I have functionality in BeginRequest event in global.asax which parse request url, check some parts of this and redirect user to another url.
Problem: how to generate url from routeName. I want to do this, because if route will be changed, redirect functionality will be working. I don't like code:
String.Format("{0}/{1}/{2}", host, part1, part2);
In view I can use Url.RouteUrl, but in global.asax i have to create UrlHelper object manually with RequestContext a开发者_如何学Pythonnd RouteData parameters. Where can i get the routedata object?
I have functionality in BeginRequest event in global.asax which parse request url, check some parts of this and redirect user to another url.
A more MVCish way to achieve this would be to use a custom action filter and perform this processing in the OnActionExecuting method which will be called before the controller action is invoked:
public class CustomFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// read some value from the request
string value = filterContext.RequestContext.RouteData.Values["someValue"] as string;
if (!IsValueValid(value))
{
// if the value is invalid redirect to some controller action
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new
{
action = "foo",
controller = "bar"
})
);
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
And now all that's left is to decorate your base controller with this attribute so that it applies to all actions.
精彩评论