简体   繁体   中英

The easiest way to get an instance of IRouter outside of controller class

I have an ASP.NET Core app which uses Mvc and OpenID Connect Auth.

In OpenID Events handler I want to handle the case when user declines consent screen on auth server, and I want to redirect the user to specific page, generating the redirect URL using router. I just don't like hardcoded URLs.

So, I had to implement the custom UseMvc method that returns IRouter back to calling method via out-parameter. Then I can save it to Startup method's property and use from every method inside it.

The problem is that my solutions seems incorrect to me, like there should be a simpler way to accomplish what I want. Just curious if someone could point me in right direction.

My code is here . The custom method I mentioned is here . And it is called there , so that the resolved router can be further used here .

You can get access to the routers as long as your code runs after the routing middleware (which as added by UseMvc() . So any custom middleware you might add that runs before MVC will not have access to the routes.

Basically any kind of MVC constructs like controllers, filters, tag helpers, etc will have access to the routers as in any of:

var routers = httpContext.GetRouteData().Routers;
var routers httpContext.Features.Get<IRoutingFeature>().RouteData.Routers;

But if your code is already an MVC construct, then you are better off using the IUrlHelper to generate the urls using any of its methods like:

urlHelper.Action("Index", "Home");

The IUrlHeleper is readily available in multiple places (like the Url property inside the Controller derived classes), but you can also get it using DI as in this question . (As long as the code where you resolve it using DI is running after the routing middleware!)

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