dotnet / dotnet/AspNetCore.Docs
Could you add recommendation on transforming input parameters.
- Dominant language
- C#
- Stars
- 13.1k
- Forks
- 24.6k
- Avg merge
- 1d 3h
- Merged PRs (30d)
- 97
Description
### Description
There is a section about Route Contstraints and Outbound Parameter transformers.
I can use the letter one to generate urls which will contain both slug and id: `slug:123`
But how do I extract id when I recieve this url back?
I tried to do it in implementation of RouteConstraint:
```
public sealed class SlugWithIdRouteConstraint : IRouteConstraint
{
public bool Match(
HttpContext? httpContext,
IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.UrlGeneration)
{
return true;
}
var paramValue = values[routeKey];
if (paramValue is not string slugWithId)
{
return false;
}
var parts = slugWithId.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length < 2)
{
return false;
}
var id = parts[^1];
// Is it ok to replace the value here?!
values[routeKey] = id;
return true;
}
}
```
and it worked, but I am not sure it's safe to do so.
I also tried the same approach for url generation, but `UrlGenerator` clones route values and the changes are not picked up after it checks the constraints. However, implmenting outbound parameter transformer works fine.
**Is this the way to go for transforming input values?**
Or sohuld I use special type like:
```
readonly record struct IdWithSlug(TId Id, string Slug);
```
and create a model binder for it?
Also, is it possible to apply outbound parameter transformer unconditionally that is without specifying transformer name in the route?
Be default LinkGenerator calls `.ToString()` for parameters without transformers, but I'd prefer to keep `ToString()` as it is and use transformer to generate a url component.
### Page URL
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-8.0#parameter-transformers
### Content source URL
https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/routing.md
### Document ID
86aeab13-1c25-9fc1-4e56-0390cb40c242
### Article author
@tdykstra
Contributor guide
Assessment
This issue has not been assessed yet.