Add friendly error message to UrlHelper for when there is no IRouter (#8145)

This commit is contained in:
James Newton-King 2019-03-15 10:14:07 -07:00 committed by GitHub
parent 694dcae53e
commit 47fab927a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 1 deletions

View File

@ -32,7 +32,21 @@ namespace Microsoft.AspNetCore.Mvc.Routing
/// Gets the top-level <see cref="IRouter"/> associated with the current request. Generally an
/// <see cref="IRouteCollection"/> implementation.
/// </summary>
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];
}
}
/// <inheritdoc />
public override string Action(UrlActionContext actionContext)

View File

@ -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<InvalidOperationException>(() => 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);