I am trying to create first API app witn vNext, being familiar with WebAPI. I'd like to use attribute routes with type constraints. Where do I write some sort of configuration to map constraint name to custom classes/enums? I tried Configure
method in Startup.cs
but have no idea what to do with IApplicationBuilder
. Searching at https://github.com/aspnet/Routing gave nothing.
I suppose, there should be a place to plug in this piece of code somewhere (for enums constraint):
routes.MapAttributeRoutes(cfg =>
{
// ...
cfg.InlineRouteConstraints.Add("customenum", typeof(EnumRouteConstraint<MyEnum>));
});
The inline constraints are configured in options
. The pattern for defining options is a common pattern in ASPNET 5, the code below is in Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection serviceCollection)
{
/// rest of the code
serviceCollection.Configure<RouteOptions>(routeOptions =>
{
routeOptions =>
routeOptions.ConstraintMap
.Add("yourstring", typeof(YourConstraintType)));
}
}
Since the options definition in startup area of the code changes across versions, I pasted something that works in latest bits. You might have to adjust based on what version you have in your project.
Here is how MVC adds the custom exists
constraint. Note this gets called from AddMvc()
.
Here is the MVC startup.cs sample.
Here is the issue tracking adding the sample and test for this scenario.
Also note that we now support inline constraints also in conventional routes.