受欢迎的博客标签

it is possible to decide at runtime the controller, action and route tokens that a request will be dispatched to. The idea is to map a route pattern to a dynamic route handler, like this:

app.UseEndpoints(endpoints =>
{
    endpoints.MapDynamicControllerRoute<SearchValueTransformer>("search/{**product}");
});

This maps a route of “/search/<anything>” to a class SearchValueTransformer, which is then responsible for supplying values for the controller and action.

This SeachValueTransformer class must inherit from DynamicRouteValueTransformer, this is the abstract base class for all dynamic route handling, and it only has one method to implement, TransformAsync. The example I am providing here is that of a service that receives some random query for a product on the URL and then decides to which controller it will be forwarded to. A sample implementation of this class would be:

   class SearchValueTransformer : DynamicRouteValueTransformer
    {
        private readonly IProductLocator _productLocator; 
        public SearchValueTransformer(IProductLocator productLocator) 
        { 
            this._productLocator = productLocator;
        }
        public override async ValueTask TransformAsync(HttpContext httpContext, RouteValueDictionary values)
        {
            var productString = values[“product”] as string;
            var id = await this._productLocator.FindProduct(“product”, out var controller); 
            values[“controller”] = controller; 
            values[“action”] = “Get”; values[“id”] = id; 
            return values; 
        }
    }

The SearchValueTransformer needs to be registered in the dependency:

services.AddSingleton<SearchValueTransformer>();

The actual implementation,  it must apply some logic to the product passed in the URL to decide which controller should be used for search it, and then return some reference and a controller responsible for returning information about it. This interface and its implementation must also be registered: