Add friendly error message to UrlHelper for when there is no IRouter (#8145)
This commit is contained in:
parent
694dcae53e
commit
47fab927a1
|
|
@ -32,7 +32,21 @@ namespace Microsoft.AspNetCore.Mvc.Routing
|
||||||
/// Gets the top-level <see cref="IRouter"/> associated with the current request. Generally an
|
/// Gets the top-level <see cref="IRouter"/> associated with the current request. Generally an
|
||||||
/// <see cref="IRouteCollection"/> implementation.
|
/// <see cref="IRouteCollection"/> implementation.
|
||||||
/// </summary>
|
/// </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 />
|
/// <inheritdoc />
|
||||||
public override string Action(UrlActionContext actionContext)
|
public override string Action(UrlActionContext actionContext)
|
||||||
|
|
|
||||||
|
|
@ -964,6 +964,27 @@ namespace Microsoft.AspNetCore.Mvc.Routing
|
||||||
Assert.Equal("http://localhost/app/home/contact", url);
|
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 IServiceProvider CreateServices();
|
||||||
|
|
||||||
protected abstract IUrlHelper CreateUrlHelper(ActionContext actionContext);
|
protected abstract IUrlHelper CreateUrlHelper(ActionContext actionContext);
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue