diff --git a/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs b/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs index 33f7d36f3e..157c32ccff 100644 --- a/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs +++ b/src/Mvc/Mvc.Core/src/Routing/UrlHelper.cs @@ -32,7 +32,21 @@ namespace Microsoft.AspNetCore.Mvc.Routing /// Gets the top-level associated with the current request. Generally an /// implementation. /// - protected IRouter Router => ActionContext.RouteData.Routers[0]; + protected IRouter Router + { + get + { + var routers = ActionContext.RouteData.Routers; + if (routers.Count == 0) + { + throw new InvalidOperationException("Could not find an IRouter associated with the ActionContext. " + + "If your application is using endpoint routing then you can get a IUrlHelperFactory with " + + "dependency injection and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator."); + } + + return routers[0]; + } + } /// public override string Action(UrlActionContext actionContext) diff --git a/src/Mvc/Mvc.Core/test/Routing/UrlHelperTestBase.cs b/src/Mvc/Mvc.Core/test/Routing/UrlHelperTestBase.cs index b1e21e515c..a1b3da3088 100644 --- a/src/Mvc/Mvc.Core/test/Routing/UrlHelperTestBase.cs +++ b/src/Mvc/Mvc.Core/test/Routing/UrlHelperTestBase.cs @@ -964,6 +964,27 @@ namespace Microsoft.AspNetCore.Mvc.Routing Assert.Equal("http://localhost/app/home/contact", url); } + [Fact] + public void NoRouter_ErrorsWithFriendlyErrorMessage() + { + // Arrange + var urlHelper = new UrlHelper(new ActionContext + { + RouteData = new RouteData(new RouteValueDictionary()), + HttpContext = new DefaultHttpContext() + }); + + // Act + var ex = Assert.Throws(() => urlHelper.ActionLink("contact", "home")); + + // Assert + var expectedMessage = "Could not find an IRouter associated with the ActionContext. " + + "If your application is using endpoint routing then you can get a IUrlHelperFactory with " + + "dependency injection and use it to create a UrlHelper, or use Microsoft.AspNetCore.Routing.LinkGenerator."; + + Assert.Equal(expectedMessage, ex.Message); + } + protected abstract IServiceProvider CreateServices(); protected abstract IUrlHelper CreateUrlHelper(ActionContext actionContext);