From 0cf972cc432e10e90fdf4f3aa27fc9ece09a3032 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Fri, 13 Jul 2018 10:16:21 +1200 Subject: [PATCH] Error message on no dispatcher middleware in endpoint middleware (#600) --- .../EndpointMiddleware.cs | 5 ++ .../EndpointMiddlewareTest.cs | 48 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 test/Microsoft.AspNetCore.Routing.Tests/EndpointMiddlewareTest.cs diff --git a/src/Microsoft.AspNetCore.Routing/EndpointMiddleware.cs b/src/Microsoft.AspNetCore.Routing/EndpointMiddleware.cs index 5fbb596d79..d7c90728dc 100644 --- a/src/Microsoft.AspNetCore.Routing/EndpointMiddleware.cs +++ b/src/Microsoft.AspNetCore.Routing/EndpointMiddleware.cs @@ -32,6 +32,11 @@ namespace Microsoft.AspNetCore.Routing public async Task Invoke(HttpContext httpContext) { var feature = httpContext.Features.Get(); + if (feature == null) + { + throw new InvalidOperationException("Unable to execute an endpoint because the dispatcher was not run. Ensure dispatcher middleware is registered."); + } + if (feature.Invoker != null) { Log.ExecutingEndpoint(_logger, feature.Endpoint); diff --git a/test/Microsoft.AspNetCore.Routing.Tests/EndpointMiddlewareTest.cs b/test/Microsoft.AspNetCore.Routing.Tests/EndpointMiddlewareTest.cs new file mode 100644 index 0000000000..ff968fb7be --- /dev/null +++ b/test/Microsoft.AspNetCore.Routing.Tests/EndpointMiddlewareTest.cs @@ -0,0 +1,48 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging.Testing; +using Xunit; + +namespace Microsoft.AspNetCore.Routing +{ + public class EndpointMiddlewareTest + { + [Fact] + public async Task Invoke_NoFeature_ThrowFriendlyErrorMessage() + { + // Arrange + var httpContext = new DefaultHttpContext(); + httpContext.RequestServices = new ServiceProvider(); + + RequestDelegate next = (c) => + { + return Task.FromResult(null); + }; + + var middleware = new EndpointMiddleware(NullLogger.Instance, next); + + // Act + var invokeTask = middleware.Invoke(httpContext); + + // Assert + var ex = await Assert.ThrowsAsync(async () => await invokeTask); + + Assert.Equal("Unable to execute an endpoint because the dispatcher was not run. Ensure dispatcher middleware is registered.", ex.Message); + } + + private class ServiceProvider : IServiceProvider + { + public object GetService(Type serviceType) + { + throw new NotImplementedException(); + } + } + } +}