2

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.

kosmakoff
  • 368
  • 4
  • 14
  • Is there any particular reason why you want to get the `IRouter` or could you just get an [`IUrlHelper`](http://stackoverflow.com/questions/30696337/unable-to-utilize-urlhelper/30697703#30697703) and use the utility methods there to generate urls? – Daniel J.G. Oct 28 '16 at 10:03

1 Answers1

0

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!)

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
  • Good point, but doesn't work in my case. The problem is that I need to place OpenID Connect code (as well as any other authentication) before Mvc, or else it will just not work. – kosmakoff Oct 28 '16 at 11:49