Endpoint Routing in 2.2
What is it?
We’re making a big investment in routing starting in 2.2 to make it interoperate more seamlessly with middleware. For 2.2 this will start with us making a few changes to the routing model, and adding some minor features. In 3.0 the plan is to introduce a model where routing and middleware operate together naturally. This post will focus on the 2.2 improvements, we’ll discuss 3.0 a bit further in the future. So, without further ado, here are some changes coming to routing in 2.2.
How to use it?
The new routing features will be on by default for 2.2 applications using MVC.
UseMvc
and related methods with the 2.2 compatibility version will enable the new ‘Endpoint Routing’ feature set. Existing conventional routes (using MapRoute
) or attribute routes will be mapped into the new system.
public void ConfigureServices(IServiceProvider services) { ... services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } public void Configure(IApplicationBuilder app) { .... app.UseMvc(); }
If you need to specifically revert the new routing features, this can be done by setting
an option. We’ve tried to make the new endpoint routing system as backwards compatible as is feasible. Please log issues at https://github.com/aspnet/Routing if you encounter problems. We don’t plan to provide an experience in 2.2 for using the new features without MVC – our focus for right now is to make sure we can successfully shift MVC applications to the new infrastructure.
Link Generator Service
We’re introducing a new singleton service that will support generating a URL. This new service can be used from middleware, and does not require an
HttpContext
. For right now the set of things you can link to is limited to MVC actions, but this will expand in 3.0.
public class MyMiddleware { public MyMiddleware(RequestDelegate next, LinkGenerator linkGenerator) { ... } public async Task Invoke(HttpContext httpContext) { var url = _linkGenerator.GenerateLink(new { controller = "Store", action = "ListProducts" }); httpContext.Response.ContentType = "text/plain"; return httpContext.Response.WriteAsync($"Go to {url} to see some cool stuff."); } }
This looks a lot like MVC’s link generation support (
IUrlHelper
) for now — but it’s usable anywhere in your application. We plan to expand the set of things that are possible during 2.2.
Performance Improvements
One of the biggest reasons for us to revisit routing in 2.2 is to improve the performance of routing and MVC’s action selection. We still have more work to, but the results so far are promising:
This chart shows the trend of Requests per Second (RPS) of our MVC implementation of the TechEmpower plaintext benchmark. We’ve improved the RPS of this benchmark about 10% from 445kRPS to 515kRPS. To test more involved scenarios, we’ve used the Swagger/OpenAPI files published by Azure and Github to build code-generated routing benchmarks. The Azure API benchmark has 5160 distinct HTTP endpoints, and the Github benchmark has 243. The new routing system is significantly faster at processing the route table of these real world APIs than anything we’ve had before. In particular MVC’s features that select actions such as matching on HTTP methods and [Consumes(...)]
are significantly less costly.
Improvements to link generation behavior for attribute routing
We’re also using this opportunity to revisit some of the behaviors that users find confusing when using attribute routing. Razor Pages is based on MVC’s attribute routing infrastructure and so many new users have become familiar with these problems lately. Inside the team, we refer to this feature as ‘route value invalidation’. Without getting into too many details, conventional routing always invalidates extra route values when linking to another action. Attribute routing didn’t have this behavior in the past. This can lead to mistakes when linking to another action that uses the same route parameter names. Now both forms of routing invalidate values when linking to another action.
A conceptual understanding
The new routing system is called ‘Endpoint Routing’ because it represents the route table as a set of Endpoints that can be selected by the the routing system. If you’ve ever thought about how attribute routing might work in MVC, the above description should not be surprising. The new part is that a bunch of concerns traditionally handled by MVC have been pushed down to a very low level of the routing system. Endpoint routing now processes HTTP methods,
[Consumes(...)]
, versioning, and other policies that used to be part of MVC’s action selection process. In contrast to this, the existing routing system models the application is a list of ‘Routes’ that need to be processed in order. What each route does is a black-box to the routing system – you have to run the route to see if it will match. To make MVC’s conventional routing work, we flatten the list of actions multiplied by the number of routes into a list of endpoints. This flattening allows us to process all of MVC’s requirements very efficiently inside the routing system. * * *The list of endpoints gets compiled into a tree that’s easy for us to walk efficiently. This is similar to what attribute routing does today but using a different algorithm and much lower complexity. Since routing builds a graph based on the endpoints, this means that the complexity of the tree scales very directly with your usage of features. We’re confident that we can scale up this design nicely while retaining the pay-for-play characteristics.
New round-tripping route parameter syntax
We are introducing a new catch-all parameter syntax
{**myparametername}
. During link generation, the routing system will encode all the content in the value captured by this parameter except the forward slashes. Note that the old parameter syntax {*myparametername}
will continue to work as it did before. Examples: * For a route defined using the old parameter syntax : /search/{*page}
, a call to Url.Action(new { category = "admin/products" })
would generate a link /search/admin%2Fproducts
(notice that the forward slash is encoded) * For a route defined using the new parameter syntax : /search/{**page}
, a call to Url.Action(new { category = "admin/products" })
would generate a link /search/admin/products
What is coming next?
Expect more refinement and polish on the
LinkGenerator
API in the next preview. We want to make sure that this new API will support a variety of scenarios for the foreseeable future.
How can you help?
There are a few areas where you can provide useful feedback during this preview. We’re interested in any thoughts you have of course, these are a few specific things we’d like opinions on. The best place to provide feedback is by opening issues at
https://github.com/aspnet/Routing What are you using IRouter</span>
for? The ‘Endpoint Routing’ system doesn’t support IRouter
-based extensibility, including inheriting from Route
. We want what you’re using IRouter
for today so we can figure out how to accomplish those things in the future. What are you using IActionConstraint
for? ‘Endpoint Routing’ supports IActionConstraint
-based extensibility from MVC, but we’re trying to find better ways to accomplish these tasks. What are your ‘most wanted’ issues from Routing? We’ve revisited a bunch of old closed bugs and brought back a few for reconsideration. If you feel like there are missing details or bugs in routing that we should consider please let us know.
Caveats and notes
We’ve worked to make the new routing system backwards compatible where possible. If you run into issues we’d love for you to report them at
https://github.com/aspnet/Routing. DataTokens are not supported in 2.2.0-preview1. We plan to address this for the next preview. By nature the new routing system does not support IRouter
based extensibility. Generating links inside MVC to conventionally routed actions that don’t yet exist will fail (resulting in the empty string). This is in contrast to the current MVC behavior where linking usually succeeds even if the action being linked hasn’t been defined yet. We know that the performance of link generation will be bad in 2.2.0-preview1. We worked hard to get the API definitions in so that you could try it out, and ignored performance. Expect the performance of URL generation to improve significantly for the next preview. Endpoint routing does not support WebApiCompatShim. You must use the 2.1 compatibility switch to continue using the compat shim.
Is the repository link correct? I have an issue. I want to use the endpoint routing in 2.2 but the RouteData.Routers property is empty when I turn it on through "EnableEndpointRouting = true;". How can I access the route table in, say, a controller. I want to use the pattern matcher to get route values from a path string. For example, "/Home/Index" would become a RouteValuesDictionary with controller = Home and action = Index. With...