简体   繁体   中英

How to Register Custom IRouter in .Net 7 MVC Application?

I have a custom IRouter implementation and I can't figure out how to register it in a.Net 7 MVC application.

What I am trying to accomplish is this: Incoming requests have the form of https://example.com/{id} and when such a request comes in I need to hit the database to retrieve the controller and action for that {id} , do some checks on it and if everything looks right pass the request on to the default router along with the entire RequestContext. The reason behind that is that such an url is valid only for a given time and a subset of visiting users. Also the underlying action and controller must not be guessable by looking at the url.

What I came up with is a cutom IRouter implementation (which also allows me to create those Urls) but I can't seem to figure out how to register on application startup.

Is using a custom IRouter still the right approach in.Net 7? How do I register one? Or am I totally on the wrong track?

One option is to switch back from endpoint routing:

builder.Services.AddMvc(options => options.EnableEndpointRouting = false); 

app.UseMvc(routeBuilder => routeBuilder.Routes.Add(new CustomRouter(routeBuilder.DefaultHandler)));

UPD

Alternative approach is to use MapDynamicControllerRoute . Something along this lines:

builder.Services.AddScoped<MyDynamic>();
// ...
app.MapDynamicControllerRoute<MyDynamic>("/{*internalid}");

public class MyDynamic: DynamicRouteValueTransformer
{
    public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
    {
        if (values.TryGetValue("internalid", out var value) && value is string s && s == "777") // simulate some search for id
        {
            values["controller"] = "Home";
            values["action"] = "test";
        }
        return new ValueTask<RouteValueDictionary>(values);
    }
}

Note that since you are still using the default routing pipeline this looks like security through obscurity which in general is not a good approach and probably you should better implement appropriate security restrictions (you should not rely on the "impossibility" to guess the actual routes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM