Add logging to ActionResults and ControllerActionInvoker

This commit is contained in:
ryanbrandenburg 2015-10-20 12:51:11 -07:00 committed by Ryan Nowak
parent 5bb9759166
commit da731fc641
51 changed files with 908 additions and 79 deletions

View File

@ -5,6 +5,9 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -52,18 +55,23 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var auth = context.HttpContext.Authentication;
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ChallengeResult>();
var authentication = context.HttpContext.Authentication;
if (AuthenticationSchemes.Count > 0)
{
foreach (var scheme in AuthenticationSchemes)
{
await auth.ChallengeAsync(scheme, Properties);
await authentication.ChallengeAsync(scheme, Properties);
}
}
else
{
await auth.ChallengeAsync(Properties);
await authentication.ChallengeAsync(Properties);
}
logger.ChallengeResultExecuting(AuthenticationSchemes);
}
}
}

View File

@ -7,6 +7,9 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc
@ -40,6 +43,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ContentResult>();
var response = context.HttpContext.Response;
var contentTypeHeader = ContentType;
@ -59,6 +65,8 @@ namespace Microsoft.AspNet.Mvc
response.StatusCode = StatusCode.Value;
}
logger.ContentResultExecuting(contentTypeHeader);
if (Content != null)
{
var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();

View File

@ -103,7 +103,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
}
}
private static object[] PrepareArguments(
public static object[] PrepareArguments(
IDictionary<string, object> actionParameters,
ParameterInfo[] declaredParameterInfos)
{

View File

@ -10,6 +10,7 @@ using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Internal;
@ -144,14 +145,23 @@ namespace Microsoft.AspNet.Mvc.Controllers
protected override async Task<IActionResult> InvokeActionAsync(ActionExecutingContext actionExecutingContext)
{
var actionMethodInfo = _descriptor.MethodInfo;
var arguments = ControllerActionExecutor.PrepareArguments(
actionExecutingContext.ActionArguments,
actionMethodInfo.GetParameters());
Logger.ActionMethodExecuting(actionExecutingContext, arguments);
var actionReturnValue = await ControllerActionExecutor.ExecuteAsync(
actionMethodInfo,
actionExecutingContext.Controller,
actionExecutingContext.ActionArguments);
arguments);
var actionResult = CreateActionResult(
actionMethodInfo.ReturnType,
actionReturnValue);
Logger.ActionMethodExecuted(actionExecutingContext, actionResult);
return actionResult;
}

View File

@ -29,7 +29,6 @@ namespace Microsoft.AspNet.Mvc.Controllers
private readonly IReadOnlyList<IModelValidatorProvider> _modelValidatorProviders;
private readonly IReadOnlyList<IValueProviderFactory> _valueProviderFactories;
private readonly IActionBindingContextAccessor _actionBindingContextAccessor;
private readonly ILogger _logger;
private readonly DiagnosticSource _diagnosticSource;
private readonly int _maxModelValidationErrors;
@ -132,7 +131,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
_modelValidatorProviders = modelValidatorProviders;
_valueProviderFactories = valueProviderFactories;
_actionBindingContextAccessor = actionBindingContextAccessor;
_logger = logger;
Logger = logger;
_diagnosticSource = diagnosticSource;
_maxModelValidationErrors = maxModelValidationErrors;
}
@ -153,6 +152,8 @@ namespace Microsoft.AspNet.Mvc.Controllers
protected object Instance { get; private set; }
protected ILogger Logger { get; }
/// <summary>
/// Called to create an instance of an object which will act as the reciever of the action invocation.
/// </summary>
@ -296,7 +297,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
}
else
{
_logger.LogWarning(AuthorizationFailureLogMessage, current.FilterAsync.GetType().FullName);
Logger.LogWarning(AuthorizationFailureLogMessage, current.FilterAsync.GetType().FullName);
}
}
else if (current.Filter != null)
@ -310,7 +311,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
}
else
{
_logger.LogWarning(AuthorizationFailureLogMessage, current.Filter.GetType().FullName);
Logger.LogWarning(AuthorizationFailureLogMessage, current.Filter.GetType().FullName);
}
}
else
@ -366,7 +367,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
// If we get here then the filter didn't call 'next' indicating a short circuit
if (_resourceExecutingContext.Result != null)
{
_logger.LogVerbose(
Logger.LogVerbose(
ResourceFilterShortCircuitLogMessage,
item.FilterAsync.GetType().FullName);
@ -387,8 +388,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
if (_resourceExecutingContext.Result != null)
{
// Short-circuited by setting a result.
_logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
Logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
await InvokeResultAsync(_resourceExecutingContext.Result);
@ -506,7 +506,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
if (_exceptionContext.Exception == null)
{
_logger.LogVerbose(
Logger.LogVerbose(
ExceptionFilterShortCircuitLogMessage,
current.FilterAsync.GetType().FullName);
}
@ -527,7 +527,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
if (_exceptionContext.Exception == null)
{
_logger.LogVerbose(
Logger.LogVerbose(
ExceptionFilterShortCircuitLogMessage,
current.Filter.GetType().FullName);
}
@ -608,7 +608,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
{
// If we get here then the filter didn't call 'next' indicating a short circuit
_logger.LogVerbose(ActionFilterShortCircuitLogMessage, item.FilterAsync.GetType().FullName);
Logger.LogVerbose(ActionFilterShortCircuitLogMessage, item.FilterAsync.GetType().FullName);
_actionExecutedContext = new ActionExecutedContext(
_actionExecutingContext,
@ -628,7 +628,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
{
// Short-circuited by setting a result.
_logger.LogVerbose(ActionFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
Logger.LogVerbose(ActionFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
_actionExecutedContext = new ActionExecutedContext(
_actionExecutingContext,
@ -752,8 +752,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
if (_resultExecutedContext == null || _resultExecutingContext.Cancel == true)
{
// Short-circuited by not calling next || Short-circuited by setting Cancel == true
_logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.FilterAsync.GetType().FullName);
Logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.FilterAsync.GetType().FullName);
_resultExecutedContext = new ResultExecutedContext(
_resultExecutingContext,
@ -772,8 +771,7 @@ namespace Microsoft.AspNet.Mvc.Controllers
if (_resultExecutingContext.Cancel == true)
{
// Short-circuited by setting Cancel == true
_logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
Logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.Filter.GetType().FullName);
_resultExecutedContext = new ResultExecutedContext(
_resultExecutingContext,

View File

@ -4,6 +4,9 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc
@ -67,6 +70,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory?.CreateLogger<FileResult>();
var response = context.HttpContext.Response;
response.ContentType = ContentType.ToString();
@ -77,11 +83,12 @@ namespace Microsoft.AspNet.Mvc
// detached and stored in a separate file. If the receiving MUA writes
// the entity to a file, the suggested filename should be used as a
// basis for the actual filename, where possible.
var cd = new ContentDispositionHeaderValue("attachment");
cd.SetHttpFileName(FileDownloadName);
context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = cd.ToString();
var contentDisposition = new ContentDispositionHeaderValue("attachment");
contentDisposition.SetHttpFileName(FileDownloadName);
context.HttpContext.Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString();
}
logger.FileResultExecuting(FileDownloadName);
return WriteFileAsync(response);
}

View File

@ -2,6 +2,9 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -34,6 +37,11 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var factory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = factory.CreateLogger<HttpStatusCodeResult>();
logger.HttpStatusCodeResultExecuting(StatusCode);
context.HttpContext.Response.StatusCode = StatusCode;
}
}

View File

@ -9,6 +9,7 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.AspNet.Mvc.Internal;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Net.Http.Headers;
@ -125,7 +126,9 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
"'{ContentType}' to write the response.",
selectedFormatter.GetType().FullName,
formatterContext.ContentType);
Logger.ObjectResultExecuting(context);
result.OnFormatting(context);
return selectedFormatter.WriteAsync(formatterContext);
}

View File

@ -0,0 +1,28 @@
// 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.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ChallengeResultLoggerExtenstions
{
private static Action<ILogger, string[], Exception> _challengeResultExecuting;
static ChallengeResultLoggerExtenstions()
{
_challengeResultExecuting = LoggerMessage.Define<string[]>(
LogLevel.Information,
1,
"Executing ChallengeResult with authentication schemes ({Schemes}).");
}
public static void ChallengeResultExecuting(this ILogger logger, IList<string> schemes)
{
_challengeResultExecuting(logger, schemes.ToArray(), null);
}
}
}

View File

@ -0,0 +1,27 @@
// 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 Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ContentResultLoggerExtensions
{
private static Action<ILogger, string, Exception> _contentResultExecuting;
static ContentResultLoggerExtensions()
{
_contentResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing ContentResult with HTTP Response ContentType of {ContentType}");
}
public static void ContentResultExecuting(this ILogger logger, MediaTypeHeaderValue contentType)
{
_contentResultExecuting(logger, contentType?.MediaType, null);
}
}
}

View File

@ -0,0 +1,61 @@
// 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 Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ControllerActionInvokerLoggerExtensions
{
private static Action<ILogger, string, string[], ModelValidationState, Exception> _actionMethodExecuting;
private static Action<ILogger, string, string, Exception> _actionMethodExecuted;
static ControllerActionInvokerLoggerExtensions()
{
_actionMethodExecuting = LoggerMessage.Define<string, string[], ModelValidationState>(
LogLevel.Information,
1,
"Executing action method {ActionName} with arguments ({Arguments}) - ModelState is {ValidationState}'");
_actionMethodExecuted = LoggerMessage.Define<string, string>(
LogLevel.Information,
2,
"Executed action method {ActionName}, returned result {ActionResult}.'");
}
public static void ActionMethodExecuting(this ILogger logger, ActionExecutingContext context, object[] arguments)
{
if (logger.IsEnabled(LogLevel.Information))
{
var actionName = context.ActionDescriptor.DisplayName;
string[] convertedArguments;
if (arguments == null)
{
convertedArguments = null;
}
else
{
convertedArguments = new string[arguments.Length];
for (var i = 0; i < arguments.Length; i++)
{
convertedArguments[i] = Convert.ToString(arguments[i]);
}
}
var validationState = context.ModelState.ValidationState;
_actionMethodExecuting(logger, actionName, convertedArguments, validationState, null);
}
}
public static void ActionMethodExecuted(this ILogger logger, ActionExecutingContext context, IActionResult result)
{
var actionName = context.ActionDescriptor.DisplayName;
_actionMethodExecuted(logger, actionName, Convert.ToString(result), null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class FileResultLoggerExtensions
{
private static Action<ILogger, string, Exception> _fileResultExecuting;
static FileResultLoggerExtensions()
{
_fileResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing FileResult, sending file as {FileDownloadName}");
}
public static void FileResultExecuting(this ILogger logger, string fileDownloadName)
{
_fileResultExecuting(logger, fileDownloadName, null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class HttpStatusCodeLoggerExtensions
{
private static Action<ILogger, int, Exception> _httpStatusCodeResultExecuting;
static HttpStatusCodeLoggerExtensions()
{
_httpStatusCodeResultExecuting = LoggerMessage.Define<int>(
LogLevel.Information,
1,
"Executing HttpStatusCodeResult, setting HTTP status code {StatusCode}");
}
public static void HttpStatusCodeResultExecuting(this ILogger logger, int statusCode)
{
_httpStatusCodeResultExecuting(logger, statusCode, null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class JsonResultLoggerExtensions
{
private static Action<ILogger, string, Exception> _jsonResultExecuting;
static JsonResultLoggerExtensions()
{
_jsonResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing JsonResult, writing value {Value}.");
}
public static void JsonResultExecuting(this ILogger logger, object value)
{
_jsonResultExecuting(logger, Convert.ToString(value), null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ObjectResultExecutorLoggerExtensions
{
private static Action<ILogger, string, Exception> _objectResultExecuting;
static ObjectResultExecutorLoggerExtensions()
{
_objectResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing ObjectResult, writing value {Value}.");
}
public static void ObjectResultExecuting(this ILogger logger, object value)
{
_objectResultExecuting(logger, Convert.ToString(value), null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class RedirectResultLoggerExtensions
{
private static Action<ILogger, string, Exception> _redirectResultExecuting;
static RedirectResultLoggerExtensions()
{
_redirectResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing RedirectResult, redirecting to {Destination}.");
}
public static void RedirectResultExecuting(this ILogger logger, string destination)
{
_redirectResultExecuting(logger, destination, null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class RedirectToActionResultLoggerExtensions
{
private static Action<ILogger, string, Exception> _redirectToActionResultExecuting;
static RedirectToActionResultLoggerExtensions()
{
_redirectToActionResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing RedirectResult, redirecting to {Destination}.");
}
public static void RedirectToActionResultExecuting(this ILogger logger, string destination)
{
_redirectToActionResultExecuting(logger, destination, null);
}
}
}

View File

@ -0,0 +1,26 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class RedirectToRouteResultLoggerExtensions
{
private static Action<ILogger, string, string, Exception> _redirectToRouteResultExecuting;
static RedirectToRouteResultLoggerExtensions()
{
_redirectToRouteResultExecuting = LoggerMessage.Define<string, string>(
LogLevel.Information,
1,
"Executing RedirectToRouteResult, redirecting to {Destination} from route {RouteName}.");
}
public static void RedirectToRouteResultExecuting(this ILogger logger, string destination, string routeName)
{
_redirectToRouteResultExecuting(logger, destination, routeName, null);
}
}
}

View File

@ -36,7 +36,9 @@ namespace Microsoft.AspNet.Mvc
public override Task ExecuteResultAsync(ActionContext context)
{
var executor = context.HttpContext.RequestServices.GetRequiredService<ObjectResultExecutor>();
return executor.ExecuteAsync(context, this);
var result = executor.ExecuteAsync(context, this);
return result;
}
/// <summary>

View File

@ -3,8 +3,10 @@
using System;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -65,6 +67,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<RedirectResult>();
var urlHelper = GetUrlHelper(context);
// IsLocalUrl is called to handle Urls starting with '~/'.
@ -74,6 +79,7 @@ namespace Microsoft.AspNet.Mvc
destinationUrl = urlHelper.Content(Url);
}
logger.RedirectResultExecuting(destinationUrl);
context.HttpContext.Response.Redirect(destinationUrl, Permanent);
}

View File

@ -4,8 +4,10 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -48,6 +50,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<RedirectToActionResult>();
var urlHelper = GetUrlHelper(context);
var destinationUrl = urlHelper.Action(ActionName, ControllerName, RouteValues);
@ -56,6 +61,7 @@ namespace Microsoft.AspNet.Mvc
throw new InvalidOperationException(Resources.NoRoutesMatched);
}
logger.RedirectToActionResultExecuting(destinationUrl);
context.HttpContext.Response.Redirect(destinationUrl, Permanent);
}

View File

@ -4,9 +4,11 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.Core;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -49,6 +51,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<RedirectToRouteResult>();
var urlHelper = GetUrlHelper(context);
var destinationUrl = urlHelper.RouteUrl(RouteName, RouteValues);
@ -57,6 +62,7 @@ namespace Microsoft.AspNet.Mvc
throw new InvalidOperationException(Resources.NoRoutesMatched);
}
logger.RedirectToRouteResultExecuting(destinationUrl, RouteName);
context.HttpContext.Response.Redirect(destinationUrl, Permanent);
}

View File

@ -5,9 +5,11 @@ using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Microsoft.AspNet.Mvc.Logging;
namespace Microsoft.AspNet.Mvc
{
@ -72,6 +74,9 @@ namespace Microsoft.AspNet.Mvc
throw new ArgumentNullException(nameof(context));
}
var loggerFactory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<JsonResult>();
var response = context.HttpContext.Response;
var contentTypeHeader = ContentType;
@ -107,6 +112,8 @@ namespace Microsoft.AspNet.Mvc
.SerializerSettings;
}
logger.JsonResultExecuting(Value);
using (var writer = new HttpResponseStreamWriter(response.Body, contentTypeHeader.Encoding))
{
using (var jsonWriter = new JsonTextWriter(writer))

View File

@ -0,0 +1,27 @@
// 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 Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class PartialViewResultExecutorLoggerExtensions
{
private static Action<ILogger, string, Exception> _partialViewResultExecuting;
static PartialViewResultExecutorLoggerExtensions()
{
_partialViewResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing PartialViewResult, running view at path {Path}.");
}
public static void PartialViewResultExecuting(this ILogger logger, IView view)
{
_partialViewResultExecuting(logger, view.Path, null);
}
}
}

View File

@ -0,0 +1,49 @@
// 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 Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ViewComponentResultLoggerExtensions
{
private static Action<ILogger, string, string[], Exception> _viewComponentResultExecuting;
static ViewComponentResultLoggerExtensions()
{
_viewComponentResultExecuting = LoggerMessage.Define<string, string[]>(
LogLevel.Information,
1,
"Executing ViewComponentResult, running {ViewComponentName} with arguments ({Arguments}).");
}
public static void ViewComponentResultExecuting(this ILogger logger, string viewComponentName, object[] arguments)
{
if (logger.IsEnabled(LogLevel.Information))
{
var formattedArguments = new string[arguments.Length];
for (var i = 0; i < arguments.Length; i++)
{
formattedArguments[i] = Convert.ToString(arguments[i]);
}
_viewComponentResultExecuting(logger, viewComponentName, formattedArguments, null);
}
}
public static void ViewComponentResultExecuting(this ILogger logger, Type viewComponentType, object[] arguments)
{
if (logger.IsEnabled(LogLevel.Information))
{
var formattedArguments = new string[arguments.Length];
for (var i = 0; i < arguments.Length; i++)
{
formattedArguments[i] = Convert.ToString(arguments[i]);
}
_viewComponentResultExecuting(logger, viewComponentType.Name, formattedArguments, null);
}
}
}
}

View File

@ -0,0 +1,27 @@
// 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 Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNet.Mvc.Logging
{
public static class ViewResultExecutorLoggerExtensions
{
private static Action<ILogger, string, Exception> _viewResultExecuting;
static ViewResultExecutorLoggerExtensions()
{
_viewResultExecuting = LoggerMessage.Define<string>(
LogLevel.Information,
1,
"Executing ViewResult, running view at path {Path}.");
}
public static void ViewResultExecuting(this ILogger logger, IView view)
{
_viewResultExecuting(logger, view.Path, null);
}
}
}

View File

@ -4,12 +4,14 @@
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Mvc.ViewFeatures.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Net.Http.Headers;
@ -72,6 +74,9 @@ namespace Microsoft.AspNet.Mvc
var htmlHelperOptions = services.GetRequiredService<IOptions<MvcViewOptions>>().Value.HtmlHelperOptions;
var viewComponentHelper = services.GetRequiredService<IViewComponentHelper>();
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ViewComponentResult>();
var viewData = ViewData;
if (viewData == null)
{
@ -124,10 +129,12 @@ namespace Microsoft.AspNet.Mvc
}
else if (ViewComponentType == null)
{
logger.ViewComponentResultExecuting(ViewComponentName, Arguments);
await viewComponentHelper.RenderInvokeAsync(ViewComponentName, Arguments);
}
else
{
logger.ViewComponentResultExecuting(ViewComponentType, Arguments);
await viewComponentHelper.RenderInvokeAsync(ViewComponentType, Arguments);
}
}

View File

@ -5,6 +5,7 @@ using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
@ -134,6 +135,8 @@ namespace Microsoft.AspNet.Mvc.ViewFeatures
throw new ArgumentNullException(nameof(viewResult));
}
Logger.PartialViewResultExecuting(view);
return ExecuteAsync(
actionContext,
view,

View File

@ -5,6 +5,7 @@ using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.AspNet.Mvc.Logging;
using Microsoft.AspNet.Mvc.ViewEngines;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.OptionsModel;
@ -134,6 +135,9 @@ namespace Microsoft.AspNet.Mvc.ViewFeatures
throw new ArgumentNullException(nameof(viewResult));
}
Logger.ViewResultExecuting(view);
return ExecuteAsync(
actionContext,
view,

View File

@ -6,6 +6,9 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Moq;
using Xunit;
@ -18,7 +21,10 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var result = new ChallengeResult("", null);
var httpContext = new Mock<HttpContext>();
httpContext.SetupGet(c => c.RequestServices).Returns(CreateServices().BuildServiceProvider());
var auth = new Mock<AuthenticationManager>();
httpContext.Setup(o => o.Authentication).Returns(auth.Object);
@ -41,7 +47,10 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var result = new ChallengeResult(new string[] { }, null);
var httpContext = new Mock<HttpContext>();
httpContext.SetupGet(c => c.RequestServices).Returns(CreateServices().BuildServiceProvider());
var auth = new Mock<AuthenticationManager>();
httpContext.Setup(o => o.Authentication).Returns(auth.Object);
@ -58,5 +67,12 @@ namespace Microsoft.AspNet.Mvc
// Assert
auth.Verify(c => c.ChallengeAsync((AuthenticationProperties)null), Times.Exactly(1));
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
}
}

View File

@ -9,7 +9,11 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
@ -94,7 +98,7 @@ namespace Microsoft.AspNet.Mvc
Encoding = Encoding.ASCII
}
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Features.Set<IHttpBufferingFeature>(new TestBufferingFeature());
var memoryStream = new MemoryStream();
httpContext.Response.Body = memoryStream;
@ -215,9 +219,21 @@ namespace Microsoft.AspNet.Mvc
new ActionDescriptor());
}
private static IServiceCollection CreateServices(params ViewComponentDescriptor[] descriptors)
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
return new DefaultHttpContext();
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}

View File

@ -18,6 +18,7 @@ using Microsoft.AspNet.Mvc.ModelBinding;
using Microsoft.AspNet.Mvc.ModelBinding.Validation;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.OptionsModel;
@ -1976,13 +1977,17 @@ namespace Microsoft.AspNet.Mvc.Controllers
}
var httpContext = new Mock<HttpContext>(MockBehavior.Loose);
var httpRequest = new DefaultHttpContext().Request;
var httpResponse = new DefaultHttpContext().Response;
var http = GetHttpContext();
var httpRequest = http.Request;
var httpResponse = http.Response;
httpContext.SetupGet(c => c.Request).Returns(httpRequest);
httpContext.SetupGet(c => c.Response).Returns(httpResponse);
httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>)))
.Returns(new Mock<ILogger<ObjectResult>>().Object);
httpContext
.Setup(o => o.RequestServices.GetService(typeof(ILoggerFactory)))
.Returns(NullLoggerFactory.Instance);
httpResponse.Body = new MemoryStream();
@ -2136,6 +2141,25 @@ namespace Microsoft.AspNet.Mvc.Controllers
throw _actionException;
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
public IActionResult ActionMethodWithBodyParameter([FromBody] Person bodyParam)
{
return new ObjectResult(bodyParam);

View File

@ -3,10 +3,14 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
@ -33,7 +37,7 @@ namespace Microsoft.AspNet.Mvc
// Arrange
var buffer = new byte[] { 1, 2, 3, 4, 5 };
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var outStream = new MemoryStream();
httpContext.Response.Body = outStream;
@ -56,7 +60,7 @@ namespace Microsoft.AspNet.Mvc
var expectedContentType = "text/foo; charset=us-ascii";
var buffer = new byte[] { 1, 2, 3, 4, 5 };
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var outStream = new MemoryStream();
httpContext.Response.Body = outStream;
@ -80,7 +84,7 @@ namespace Microsoft.AspNet.Mvc
var expectedContentType = "text/foo; charset=us-ascii";
var buffer = new byte[] { 1, 2, 3, 4, 5 };
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var bufferingFeature = new TestBufferingFeature();
httpContext.Features.Set<IHttpBufferingFeature>(bufferingFeature);
var outStream = new MemoryStream();
@ -99,6 +103,25 @@ namespace Microsoft.AspNet.Mvc
Assert.True(bufferingFeature.DisableResponseBufferingInvoked);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
private class TestBufferingFeature : IHttpBufferingFeature
{
public bool DisableResponseBufferingInvoked { get; private set; }

View File

@ -8,6 +8,9 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
@ -32,7 +35,7 @@ namespace Microsoft.AspNet.Mvc
// See comment in FileResult.cs detailing how the FileDownloadName should be encoded.
// Arrange
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var actionContext = CreateActionContext(httpContext);
var result = new EmptyFileResult("application/my-type")
@ -54,7 +57,7 @@ namespace Microsoft.AspNet.Mvc
public async Task ContentDispositionHeader_IsEncodedCorrectly_ForUnicodeCharacters()
{
// Arrange
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var actionContext = CreateActionContext(httpContext);
var result = new EmptyFileResult("application/my-type")
@ -77,8 +80,12 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var httpContext = new Mock<HttpContext>(MockBehavior.Strict);
httpContext.SetupSet(c => c.Response.ContentType = "application/my-type").Verifiable();
httpContext.Setup(c => c.Response.Body).Returns(Stream.Null);
httpContext
.Setup(c => c.RequestServices.GetService(typeof(ILoggerFactory)))
.Returns(NullLoggerFactory.Instance);
var actionContext = CreateActionContext(httpContext.Object);
@ -96,7 +103,7 @@ namespace Microsoft.AspNet.Mvc
public async Task ExecuteResultAsync_SetsContentDisposition_IfSpecified()
{
// Arrange
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var actionContext = CreateActionContext(httpContext);
var result = new EmptyFileResult("application/my-type")
@ -207,6 +214,23 @@ namespace Microsoft.AspNet.Mvc
Assert.Equal(expectedOutput, actual);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
private static ActionContext CreateActionContext(HttpContext context)
{
return new ActionContext(context, new RouteData(), new ActionDescriptor());

View File

@ -6,10 +6,14 @@ using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
@ -52,7 +56,7 @@ namespace Microsoft.AspNet.Mvc
var result = new FileStreamResult(mockReadStream.Object, "text/plain");
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = mockBodyStream.Object;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -76,7 +80,7 @@ namespace Microsoft.AspNet.Mvc
var originalStream = new MemoryStream(originalBytes);
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var outStream = new MemoryStream();
httpContext.Response.Body = outStream;
@ -104,7 +108,7 @@ namespace Microsoft.AspNet.Mvc
var originalStream = new MemoryStream(originalBytes);
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var outStream = new MemoryStream();
httpContext.Response.Body = outStream;
@ -130,7 +134,7 @@ namespace Microsoft.AspNet.Mvc
var originalStream = new MemoryStream(expected);
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var bufferingFeature = new TestBufferingFeature();
httpContext.Features.Set<IHttpBufferingFeature>(bufferingFeature);
var outStream = new MemoryStream();
@ -148,5 +152,22 @@ namespace Microsoft.AspNet.Mvc
Assert.Equal(expectedContentType, httpContext.Response.ContentType);
Assert.True(bufferingFeature.DisableResponseBufferingInvoked);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}

View File

@ -6,6 +6,9 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
namespace Microsoft.AspNet.Mvc
@ -26,7 +29,10 @@ namespace Microsoft.AspNet.Mvc
public async Task HttpOkResult_SetsStatusCode()
{
// Arrange
var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = CreateServices().BuildServiceProvider();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var result = new HttpOkResult();
// Act
@ -35,5 +41,12 @@ namespace Microsoft.AspNet.Mvc
// Assert
Assert.Equal(StatusCodes.Status200OK, context.HttpContext.Response.StatusCode);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
}
}

View File

@ -5,6 +5,9 @@ using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
namespace Microsoft.AspNet.Mvc
@ -17,7 +20,7 @@ namespace Microsoft.AspNet.Mvc
// Arrange
var result = new HttpStatusCodeResult(StatusCodes.Status404NotFound);
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var routeData = new RouteData();
var actionDescriptor = new ActionDescriptor();
@ -29,5 +32,22 @@ namespace Microsoft.AspNet.Mvc
// Assert
Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}

View File

@ -9,6 +9,7 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.OptionsModel;
@ -259,7 +260,7 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
HttpContext = GetHttpContext(),
};
var result = new ObjectResult("someValue");
@ -284,7 +285,7 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
HttpContext = GetHttpContext(),
};
var result = new ObjectResult("someValue");
@ -353,7 +354,7 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
HttpContext = GetHttpContext(),
};
actionContext.HttpContext.Request.Headers[HeaderNames.Accept] = acceptHeader;
@ -390,7 +391,7 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext(),
HttpContext = GetHttpContext(),
};
actionContext.HttpContext.Request.Headers[HeaderNames.Accept] = acceptHeader;
@ -401,6 +402,25 @@ namespace Microsoft.AspNet.Mvc.Infrastructure
Assert.Equal(expectedContentType, actionContext.HttpContext.Response.Headers[HeaderNames.ContentType]);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
private static TestObjectResultExecutor CreateExecutor(
IOptions<MvcOptions> options = null,
ActionBindingContext bindingContext = null)

View File

@ -8,6 +8,7 @@ using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Formatters;
using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Xunit;
@ -68,6 +69,7 @@ namespace Microsoft.AspNet.Mvc
new TestOptionsManager<MvcOptions>(),
new ActionBindingContextAccessor(),
NullLoggerFactory.Instance));
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services.BuildServiceProvider();
}

View File

@ -6,10 +6,14 @@ using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
@ -37,7 +41,7 @@ namespace Microsoft.AspNet.Mvc
// Arrange
var path = Path.GetFullPath(Path.Combine("TestFiles", "FilePathResultTestFile.txt"));
var result = new TestPhysicalFileResult(path, "text/plain");
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -62,7 +66,7 @@ namespace Microsoft.AspNet.Mvc
.Setup(s => s.SendFileAsync(path, 0, null, CancellationToken.None))
.Returns(Task.FromResult<int>(0));
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Features.Set(sendFileMock.Object);
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -83,7 +87,7 @@ namespace Microsoft.AspNet.Mvc
{
IsAscii = true
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var memoryStream = new MemoryStream();
httpContext.Response.Body = memoryStream;
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -104,7 +108,7 @@ namespace Microsoft.AspNet.Mvc
var path = Path.GetFullPath(Path.Combine(".", "TestFiles", "FilePathResultTestFile.txt"));
var result = new TestPhysicalFileResult(path, "text/plain");
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -136,7 +140,7 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var result = new TestPhysicalFileResult(path, "text/plain");
var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
var context = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
var expectedMessage = $"Path '{path}' was not rooted.";
// Act
@ -204,5 +208,22 @@ namespace Microsoft.AspNet.Mvc
}
}
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}

View File

@ -8,6 +8,7 @@ using Microsoft.AspNet.Mvc.Infrastructure;
using Microsoft.AspNet.Mvc.Routing;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
@ -110,6 +111,7 @@ namespace Microsoft.AspNet.Mvc
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<IUrlHelper>(urlHelper);
serviceCollection.AddTransient<ILoggerFactory, LoggerFactory>();
return serviceCollection.BuildServiceProvider();
}

View File

@ -8,6 +8,9 @@ using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Mvc.Routing;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Moq;
using Xunit;
@ -21,13 +24,19 @@ namespace Microsoft.AspNet.Mvc
// Arrange
var expectedUrl = "SampleAction";
var expectedPermanentFlag = false;
var httpContext = new Mock<HttpContext>();
var httpResponse = new Mock<HttpResponse>();
httpContext.Setup(o => o.Response).Returns(httpResponse.Object);
var actionContext = new ActionContext(httpContext.Object,
new RouteData(),
new ActionDescriptor());
var httpContext = new Mock<HttpContext>();
httpContext
.SetupGet(o => o.RequestServices)
.Returns(CreateServices().BuildServiceProvider());
var httpResponse = new Mock<HttpResponse>();
httpContext
.Setup(o => o.Response)
.Returns(httpResponse.Object);
var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
var urlHelper = GetMockUrlHelper(expectedUrl);
var result = new RedirectToActionResult("SampleAction", null, null)
{
@ -49,10 +58,14 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var httpContext = new Mock<HttpContext>();
httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
var actionContext = new ActionContext(httpContext.Object,
new RouteData(),
new ActionDescriptor());
httpContext
.Setup(o => o.Response)
.Returns(new Mock<HttpResponse>().Object);
httpContext
.SetupGet(o => o.RequestServices)
.Returns(CreateServices().BuildServiceProvider());
var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
var urlHelper = GetMockUrlHelper(returnValue: null);
var result = new RedirectToActionResult(null, null, null)
@ -76,5 +89,12 @@ namespace Microsoft.AspNet.Mvc
return urlHelper.Object;
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
}
}

View File

@ -10,7 +10,10 @@ using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Mvc.Routing;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Moq;
using Xunit;
@ -25,7 +28,10 @@ namespace Microsoft.AspNet.Mvc
// Arrange
var expectedUrl = "SampleAction";
var expectedPermanentFlag = false;
var httpContext = new Mock<HttpContext>();
httpContext.SetupGet(o => o.RequestServices).Returns(CreateServices().BuildServiceProvider());
var httpResponse = new Mock<HttpResponse>();
httpContext.Setup(o => o.Response).Returns(httpResponse.Object);
@ -54,10 +60,14 @@ namespace Microsoft.AspNet.Mvc
{
// Arrange
var httpContext = new Mock<HttpContext>();
httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
var actionContext = new ActionContext(httpContext.Object,
new RouteData(),
new ActionDescriptor());
httpContext
.Setup(o => o.Response)
.Returns(new Mock<HttpResponse>().Object);
httpContext
.SetupGet(o => o.RequestServices)
.Returns(CreateServices().BuildServiceProvider());
var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
var urlHelper = GetMockUrlHelper(returnValue: null);
var result = new RedirectToRouteResult(null, new Dictionary<string, object>())
@ -86,10 +96,16 @@ namespace Microsoft.AspNet.Mvc
.Verifiable();
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(sp => sp.GetService(typeof(IUrlHelper)))
serviceProvider
.Setup(sp => sp.GetService(typeof(IUrlHelper)))
.Returns(urlHelper.Object);
var httpContext = new DefaultHttpContext();
serviceProvider
.Setup(sp => sp.GetService(typeof(ILoggerFactory)))
.Returns(NullLoggerFactory.Instance);
var httpContext = GetHttpContext();
httpContext.RequestServices = serviceProvider.Object;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var result = new RedirectToRouteResult(routeName, new { id = 10 });
@ -103,6 +119,23 @@ namespace Microsoft.AspNet.Mvc
Assert.Equal(locationUrl, httpContext.Response.Headers["Location"]);
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
public static IEnumerable<object[]> RedirectToRouteData
{
get

View File

@ -7,11 +7,14 @@ using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
@ -44,10 +47,11 @@ namespace Microsoft.AspNet.Mvc
appEnvironment.Setup(app => app.WebRootFileProvider)
.Returns(GetFileProvider(path));
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = new ServiceCollection()
.AddInstance<IHostingEnvironment>(appEnvironment.Object)
.AddTransient<ILoggerFactory, LoggerFactory>()
.BuildServiceProvider();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -71,7 +75,7 @@ namespace Microsoft.AspNet.Mvc
FileProvider = GetFileProvider(path),
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -100,7 +104,7 @@ namespace Microsoft.AspNet.Mvc
.Setup(s => s.SendFileAsync(path, 0, null, CancellationToken.None))
.Returns(Task.FromResult<int>(0));
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Features.Set(sendFileMock.Object);
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -123,7 +127,7 @@ namespace Microsoft.AspNet.Mvc
IsAscii = true,
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var memoryStream = new MemoryStream();
httpContext.Response.Body = memoryStream;
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -147,7 +151,7 @@ namespace Microsoft.AspNet.Mvc
FileProvider = GetFileProvider(path),
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
@ -175,7 +179,7 @@ namespace Microsoft.AspNet.Mvc
{
FileProvider = GetFileProvider(path),
};
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
var memoryStream = new MemoryStream();
httpContext.Response.Body = memoryStream;
@ -194,7 +198,7 @@ namespace Microsoft.AspNet.Mvc
public async Task ExecuteResultAsync_WorksWithNonDiskBasedFiles()
{
// Arrange
var httpContext = new DefaultHttpContext();
var httpContext = GetHttpContext();
httpContext.Response.Body = new MemoryStream();
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var expectedData = "This is an embedded resource";
@ -249,7 +253,7 @@ namespace Microsoft.AspNet.Mvc
};
var expectedMessage = "Could not find file: " + path;
var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
var context = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
// Act
var ex = await Assert.ThrowsAsync<FileNotFoundException>(() => filePathResult.ExecuteResultAsync(context));
@ -286,6 +290,25 @@ namespace Microsoft.AspNet.Mvc
Assert.ThrowsAsync<DirectoryNotFoundException>(() => filePathResult.ExecuteResultAsync(context));
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
private IFileProvider GetFileProvider(string path)
{
var fileInfo = new Mock<IFileInfo>();

View File

@ -11,6 +11,9 @@ using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Mvc.Filters;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Moq;
using Xunit;
@ -140,6 +143,10 @@ namespace Microsoft.AspNet.Mvc.Cors
httpContext.Request.Headers.Add(CorsConstants.Origin, new[] { headers.Origin });
}
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
httpContext.RequestServices = services.BuildServiceProvider();
var method = isPreflight ? CorsConstants.PreflightHttpMethod : "GET";
httpContext.Request.Method = method;

View File

@ -11,6 +11,8 @@ using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Xunit;
@ -128,8 +130,10 @@ namespace Microsoft.AspNet.Mvc
{
var httpContext = new DefaultHttpContext();
httpContext.Response.Body = new MemoryStream();
var services = new ServiceCollection();
services.AddOptions();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;

View File

@ -75,6 +75,11 @@ namespace Microsoft.AspNet.Mvc
.Setup(v => v.Dispose())
.Verifiable();
// Used by logging
view
.SetupGet(v => v.Path)
.Returns("myview.cshtml");
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.FindPartialView(context, "myview"))

View File

@ -16,6 +16,8 @@ using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.OptionsModel;
using Microsoft.Net.Http.Headers;
using Xunit;
@ -397,6 +399,7 @@ namespace Microsoft.AspNet.Mvc
services.AddSingleton<IViewComponentActivator, DefaultViewComponentActivator>();
services.AddInstance<IViewComponentDescriptorProvider>(new FixedSetViewComponentDescriptorProvider(descriptors));
services.AddSingleton<IModelMetadataProvider, EmptyModelMetadataProvider>();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}

View File

@ -75,6 +75,10 @@ namespace Microsoft.AspNet.Mvc
.Setup(v => v.Dispose())
.Verifiable();
view
.Setup(v => v.Path)
.Returns("//location");
var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
viewEngine
.Setup(e => e.FindView(context, "myview"))

View File

@ -7,6 +7,9 @@ using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace System.Web.Http
@ -17,7 +20,7 @@ namespace System.Web.Http
public async Task ConflictResult_SetsStatusCode()
{
// Arrange
var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
var context = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
var result = new ConflictResult();
// Act
@ -26,5 +29,24 @@ namespace System.Web.Http
// Assert
Assert.Equal(StatusCodes.Status409Conflict, context.HttpContext.Response.StatusCode);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}

View File

@ -7,6 +7,9 @@ using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Abstractions;
using Microsoft.AspNet.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Framework.DependencyInjection;
using Xunit;
namespace System.Web.Http
@ -17,7 +20,7 @@ namespace System.Web.Http
public async Task InternalServerErrorResult_SetsStatusCode()
{
// Arrange
var context = new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor());
var context = new ActionContext(GetHttpContext(), new RouteData(), new ActionDescriptor());
var result = new InternalServerErrorResult();
// Act
@ -26,5 +29,24 @@ namespace System.Web.Http
// Assert
Assert.Equal(StatusCodes.Status500InternalServerError, context.HttpContext.Response.StatusCode);
}
private static IServiceCollection CreateServices()
{
var services = new ServiceCollection();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services;
}
private static HttpContext GetHttpContext()
{
var services = CreateServices();
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
}
}