Use custom route handler with MVC5 attribute routing

Using the AttributeRouting library , I was able to configure attribute routing to using a special route handler (inheriting MvcRouteHandler):

routes.MapAttributeRoutes(cfg =>
    {
        cfg.UseRouteHandler(() => new MultiCultureMvcRouteHandler());
    }
);

In addition, before MVC5, you could change the route handler of any existing route:

(routes["myroute"] as Route).RouteHandler = new MyCustomRouteHandler();

With MVC5, using attribute routing, the route collection contains inner classes (e.g. t23>), and it seems not possible to change the route property RouteHandler.

How to change the default route handler used when working with attribute routing in MVC5.1?

+4
source share
1 answer

Create your own RouteAttribute attribute.

Check out the docs here: http://msdn.microsoft.com/en-us/library/system.web.mvc.routeattribute(v=vs.118).aspx

Implement these interfaces and in the CreateRoute method you can select tokens for the RouteEntry object.

I have not tried, but something like below, you need to do some more work, but this should put you on the path.

public class MyRouteAttribute : Attribute, IDirectRouteFactory, IRouteInfoProvider
{
    public RouteEntry CreateRoute(DirectRouteFactoryContext context)
    {
        return new RouteEntry("Test", new Route("Url", new CustomRouteHandler()));
    }

    public string Name
    {
        get { throw new NotImplementedException(); }
    }

    public string Template
    {
        get { throw new NotImplementedException(); }
    }
}
0
source

Source: https://habr.com/ru/post/1531535/


All Articles