Skip to content

Add support for TryParse(HttpContext, ...) to RequestDelegateFactory #35433

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 68 additions & 16 deletions src/Http/Http.Extensions/src/RequestDelegateFactory.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
Expand Down Expand Up @@ -34,17 +35,19 @@ public static partial class RequestDelegateFactory
private static readonly MethodInfo ResultWriteResponseAsyncMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteResultWriteResponse), BindingFlags.NonPublic | BindingFlags.Static)!;
private static readonly MethodInfo StringResultWriteResponseAsyncMethod = typeof(RequestDelegateFactory).GetMethod(nameof(ExecuteWriteStringResponseAsync), BindingFlags.NonPublic | BindingFlags.Static)!;
private static readonly MethodInfo JsonResultWriteResponseAsyncMethod = GetMethodInfo<Func<HttpResponse, object, Task>>((response, value) => HttpResponseJsonExtensions.WriteAsJsonAsync(response, value, default));
private static readonly MethodInfo LogParameterBindingFailureMethod = GetMethodInfo<Action<HttpContext, string, string, string>>((httpContext, parameterType, parameterName, sourceValue) =>
Log.ParameterBindingFailed(httpContext, parameterType, parameterName, sourceValue));

private static readonly MethodInfo LogParameterBindingFailedMethod = GetMethodInfo<Action<HttpContext, string, string, string>>((httpContext, parameterType, parameterName, sourceValue) =>
Log.ParameterBindingFailed(httpContext, parameterType, parameterName, sourceValue));
private static readonly MethodInfo LogRequiredParameterNotProvidedMethod = GetMethodInfo<Action<HttpContext, string, string>>((httpContext, parameterType, parameterName) =>
Log.RequiredParameterNotProvided(httpContext, parameterType, parameterName));
private static readonly MethodInfo LogParameterBindingFromHttpContextFailedMethod = GetMethodInfo<Action<HttpContext, string, string>>((httpContext, parameterType, parameterName) =>
Log.ParameterBindingFromHttpContextFailed(httpContext, parameterType, parameterName));

private static readonly ParameterExpression TargetExpr = Expression.Parameter(typeof(object), "target");
private static readonly ParameterExpression HttpContextExpr = Expression.Parameter(typeof(HttpContext), "httpContext");
private static readonly ParameterExpression BodyValueExpr = Expression.Parameter(typeof(object), "bodyValue");
private static readonly ParameterExpression WasParamCheckFailureExpr = Expression.Variable(typeof(bool), "wasParamCheckFailure");

private static ParameterExpression HttpContextExpr => TryParseMethodCache.HttpContextExpr;
private static readonly MemberExpression RequestServicesExpr = Expression.Property(HttpContextExpr, typeof(HttpContext).GetProperty(nameof(HttpContext.RequestServices))!);
private static readonly MemberExpression HttpRequestExpr = Expression.Property(HttpContextExpr, typeof(HttpContext).GetProperty(nameof(HttpContext.Request))!);
private static readonly MemberExpression HttpResponseExpr = Expression.Property(HttpContextExpr, typeof(HttpContext).GetProperty(nameof(HttpContext.Response))!);
Expand All @@ -56,8 +59,9 @@ public static partial class RequestDelegateFactory
private static readonly MemberExpression StatusCodeExpr = Expression.Property(HttpResponseExpr, typeof(HttpResponse).GetProperty(nameof(HttpResponse.StatusCode))!);
private static readonly MemberExpression CompletedTaskExpr = Expression.Property(null, (PropertyInfo)GetMemberInfo<Func<Task>>(() => Task.CompletedTask));

private static readonly BinaryExpression TempSourceStringNotNullExpr = Expression.NotEqual(TryParseMethodCache.TempSourceStringExpr, Expression.Constant(null));
private static readonly BinaryExpression TempSourceStringNullExpr = Expression.Equal(TryParseMethodCache.TempSourceStringExpr, Expression.Constant(null));
private static ParameterExpression TempSourceStringExpr => TryParseMethodCache.TempSourceStringExpr;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cleaner

private static readonly BinaryExpression TempSourceStringNotNullExpr = Expression.NotEqual(TempSourceStringExpr, Expression.Constant(null));
private static readonly BinaryExpression TempSourceStringNullExpr = Expression.Equal(TempSourceStringExpr, Expression.Constant(null));

/// <summary>
/// Creates a <see cref="RequestDelegate"/> implementation for <paramref name="action"/>.
Expand Down Expand Up @@ -169,7 +173,7 @@ public static RequestDelegate Create(MethodInfo methodInfo, Func<HttpContext, ob

if (factoryContext.UsingTempSourceString)
{
responseWritingMethodCall = Expression.Block(new[] { TryParseMethodCache.TempSourceStringExpr }, responseWritingMethodCall);
responseWritingMethodCall = Expression.Block(new[] { TempSourceStringExpr }, responseWritingMethodCall);
}

return HandleRequestBodyAndCompileRequestDelegate(responseWritingMethodCall, factoryContext);
Expand Down Expand Up @@ -246,7 +250,11 @@ private static Expression CreateArgument(ParameterInfo parameter, FactoryContext
{
return RequestAbortedExpr;
}
else if (parameter.ParameterType == typeof(string) || TryParseMethodCache.HasTryParseMethod(parameter))
else if (TryParseMethodCache.HasTryParseHttpContextMethod(parameter))
{
return BindParameterFromTryParseHttpContext(parameter, factoryContext);
}
else if (parameter.ParameterType == typeof(string) || TryParseMethodCache.HasTryParseStringMethod(parameter))
{
// 1. We bind from route values only, if route parameters are non-null and the parameter name is in that set.
// 2. We bind from query only, if route parameters are non-null and the parameter name is NOT in that set.
Expand Down Expand Up @@ -602,7 +610,7 @@ private static Expression BindParameterFromValue(ParameterInfo parameter, Expres
var isNotNullable = underlyingNullableType is null;

var nonNullableParameterType = underlyingNullableType ?? parameter.ParameterType;
var tryParseMethodCall = TryParseMethodCache.FindTryParseMethod(nonNullableParameterType);
var tryParseMethodCall = TryParseMethodCache.FindTryParseStringMethod(nonNullableParameterType);

if (tryParseMethodCall is null)
{
Expand Down Expand Up @@ -646,16 +654,16 @@ private static Expression BindParameterFromValue(ParameterInfo parameter, Expres
// param2_local = 42;
// }

// If the parameter is nullable, create a "parsedValue" local to TryParse into since we cannot the parameter directly.
// If the parameter is nullable, create a "parsedValue" local to TryParse into since we cannot use the parameter directly.
var parsedValue = isNotNullable ? argument : Expression.Variable(nonNullableParameterType, "parsedValue");

var parameterTypeNameConstant = Expression.Constant(parameter.ParameterType.Name);
var parameterNameConstant = Expression.Constant(parameter.Name);

var failBlock = Expression.Block(
Expression.Assign(WasParamCheckFailureExpr, Expression.Constant(true)),
Expression.Call(LogParameterBindingFailureMethod,
HttpContextExpr, parameterTypeNameConstant, parameterNameConstant, TryParseMethodCache.TempSourceStringExpr));
Expression.Call(LogParameterBindingFailedMethod,
HttpContextExpr, parameterTypeNameConstant, parameterNameConstant, TempSourceStringExpr));

var tryParseCall = tryParseMethodCall(parsedValue);

Expand Down Expand Up @@ -694,14 +702,14 @@ private static Expression BindParameterFromValue(ParameterInfo parameter, Expres
var fullParamCheckBlock = !isOptional
? Expression.Block(
// tempSourceString = httpContext.RequestValue["id"];
Expression.Assign(TryParseMethodCache.TempSourceStringExpr, valueExpression),
Expression.Assign(TempSourceStringExpr, valueExpression),
// if (tempSourceString == null) { ... } only produced when parameter is required
checkRequiredParaseableParameterBlock,
// if (tempSourceString != null) { ... }
ifNotNullTryParse)
: Expression.Block(
// tempSourceString = httpContext.RequestValue["id"];
Expression.Assign(TryParseMethodCache.TempSourceStringExpr, valueExpression),
Expression.Assign(TempSourceStringExpr, valueExpression),
// if (tempSourceString != null) { ... }
ifNotNullTryParse);

Expand All @@ -721,6 +729,42 @@ private static Expression BindParameterFromRouteValueOrQueryString(ParameterInfo
return BindParameterFromValue(parameter, Expression.Coalesce(routeValue, queryValue), factoryContext);
}

private static Expression BindParameterFromTryParseHttpContext(ParameterInfo parameter, FactoryContext factoryContext)
{
// bool wasParamCheckFailure = false;
//
// // Assume "Foo param1" is the first parameter and "public static bool TryParse(HttpContext context, out Foo foo)" exists.
// Foo param1_local;
//
// if (!Foo.TryParse(httpContext, out param1_local))
// {
// wasParamCheckFailure = true;
// Log.ParameterBindingFromHttpContextFailed(httpContext, "Foo", "foo")
// }

var argument = Expression.Variable(parameter.ParameterType, $"{parameter.Name}_local");
var tryParseMethodCall = TryParseMethodCache.FindTryParseHttpContextMethod(parameter.ParameterType);

// There's no way to opt-in to using a TryParse method on HttpContext other than defining the method, so it's guaranteed to exist here.
Debug.Assert(tryParseMethodCall is not null);

var parameterTypeNameConstant = Expression.Constant(parameter.ParameterType.Name);
var parameterNameConstant = Expression.Constant(parameter.Name);

var failBlock = Expression.Block(
Expression.Assign(WasParamCheckFailureExpr, Expression.Constant(true)),
Expression.Call(LogParameterBindingFromHttpContextFailedMethod,
HttpContextExpr, parameterTypeNameConstant, parameterNameConstant));

var tryParseCall = tryParseMethodCall(argument);
var fullParamCheckBlock = Expression.IfThen(Expression.Not(tryParseCall), failBlock);

factoryContext.ExtraLocals.Add(argument);
factoryContext.ParamCheckExpressions.Add(fullParamCheckBlock);

return argument;
}

private static Expression BindParameterFromBody(ParameterInfo parameter, bool allowEmpty, FactoryContext factoryContext)
{
if (factoryContext.JsonRequestBodyType is not null)
Expand Down Expand Up @@ -982,19 +1026,27 @@ public static void RequestBodyInvalidDataException(HttpContext httpContext, Inva
public static void ParameterBindingFailed(HttpContext httpContext, string parameterTypeName, string parameterName, string sourceValue)
=> ParameterBindingFailed(GetLogger(httpContext), parameterTypeName, parameterName, sourceValue);

public static void RequiredParameterNotProvided(HttpContext httpContext, string parameterTypeName, string parameterName)
=> RequiredParameterNotProvided(GetLogger(httpContext), parameterTypeName, parameterName);

[LoggerMessage(3, LogLevel.Debug,
@"Failed to bind parameter ""{ParameterType} {ParameterName}"" from ""{SourceValue}"".",
EventName = "ParamaterBindingFailed")]
private static partial void ParameterBindingFailed(ILogger logger, string parameterType, string parameterName, string sourceValue);

public static void RequiredParameterNotProvided(HttpContext httpContext, string parameterTypeName, string parameterName)
=> RequiredParameterNotProvided(GetLogger(httpContext), parameterTypeName, parameterName);

[LoggerMessage(4, LogLevel.Debug,
@"Required parameter ""{ParameterType} {ParameterName}"" was not provided.",
EventName = "RequiredParameterNotProvided")]
private static partial void RequiredParameterNotProvided(ILogger logger, string parameterType, string parameterName);

public static void ParameterBindingFromHttpContextFailed(HttpContext httpContext, string parameterTypeName, string parameterName)
=> ParameterBindingFromHttpContextFailed(GetLogger(httpContext), parameterTypeName, parameterName);

[LoggerMessage(5, LogLevel.Debug,
@"Failed to bind parameter ""{ParameterType} {ParameterName}"" from HttpContext.",
EventName = "ParameterBindingFromHttpContextFailed")]
private static partial void ParameterBindingFromHttpContextFailed(ILogger logger, string parameterType, string parameterName);

private static ILogger GetLogger(HttpContext httpContext)
{
var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();
Expand Down
Loading