Question

I have a custom ActionFilterAttribute class that sends the user to an error screen with a link to return to a previous page.

This attribute accepts two controller/action pairs: one for the error screen action (usually the same application-wide) and another for the return action (usually the same for all actions in a controller). The idea is that when an error occurs, I don't want my users to feel lost because they don't have a way back into the application.

Right now I have four properties: two for the controller names and two for the action names. I don't like how I have hard-coded the two actions in my application. It would be nice to have friendly defaults for them. I want to be able to specify the default error action globally.

So, there are a few questions:

  • How can I globally configure a route that my attribute can reference?
  • When I need to override the defaults, what is the best way to reference a controller/action pair?

One of the problems with it being an attribute is that all parameters to the attribute have to be constant. So I can't compute an ActionResult or anything like that.

Was it helpful?

Solution

you can define Routes in RouteConfig like this:

routes.MapRoute(
                name: "Error",
                url: "error/generalerror",
                defaults: new { controller = "Error", action = "GeneralError" },
                namespaces: new[] { "YourApplication.namespace" }
            );
routes.MapRoute(
                name: "CustomError",
                url: "error/customerror",
                defaults: new { controller = "Error", action = "CustomError" },
                namespaces: new[] { "YourApplication.namespace" }
            );

Then in your ActionFilter class you can have a default two constructors

public YourFilterAttribute()
 : this("Error")
{}

public YourFilterAttribute(string route)
{
//store route in some class variable
}

That way most classes would use the attibute like this: [YourFilter] and those that need a custom route would use it: [YourFilter("CustomError")]

That way your general route is only hardcoded once in the class that it really belongs. Of course for custom error routes you can create some constant strings to clean more the code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top