Skip to content

First pass at basic query string parameters. #46545

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
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
<Compile Include="$(SharedSourceRoot)Nullable\NullableAttributes.cs" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\BoundedCacheWithFactory.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\WellKnownTypes.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\WellKnownTypeData.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\SymbolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
<Compile Include="$(SharedSourceRoot)IsExternalInit.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)HashCode.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\BoundedCacheWithFactory.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\WellKnownTypeData.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\WellKnownTypes.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)RoslynUtils\SymbolExtensions.cs" LinkBase="Shared" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Http/Http.Extensions/gen/RequestDelegateGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
lineNumber);
}
""");
}
}

return code.ToString();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.AspNetCore.Http.Generators.StaticRouteHandlerModel.Emitters;
internal static class EndpointEmitter
{
internal static string EmitParameterPreparation(this Endpoint endpoint)
{
var parameterPreparationBuilder = new StringBuilder();

foreach (var parameter in endpoint.Parameters)
{
var parameterPreparationCode = parameter switch
{
{
Source: EndpointParameterSource.SpecialType
} => parameter.EmitSpecialParameterPreparation(),
{
Source: EndpointParameterSource.Query,
} => parameter.EmitQueryParameterPreparation(),
_ => throw new Exception("Unreachable!")
};

parameterPreparationBuilder.AppendLine(parameterPreparationCode);
}

return parameterPreparationBuilder.ToString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;

namespace Microsoft.AspNetCore.Http.Generators.StaticRouteHandlerModel.Emitters;
internal static class EndpointParameterEmitter
{
internal static string EmitSpecialParameterPreparation(this EndpointParameter endpointParameter)
{
return $"""
var {endpointParameter.Name}_local = {endpointParameter.AssigningCode};
""";
}

internal static string EmitQueryParameterPreparation(this EndpointParameter endpointParameter)
{
return $$"""
var {{endpointParameter.Name}}_raw = {{endpointParameter.AssigningCode}};

if (StringValues.IsNullOrEmpty({{endpointParameter.Name}}_raw) && {{(endpointParameter.IsOptional ? "false" : "false")}})
{
httpContext.Response.StatusCode = 400;
return Task.CompletedTask;
}

var {{endpointParameter.HandlerArgument}} = {{endpointParameter.Name}}_raw.ToString();
""";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static bool SignatureEquals(Endpoint a, Endpoint b)

for (var i = 0; i < a.Parameters.Length; i++)
{
if (a.Parameters[i].Equals(b.Parameters[i]))
if (!a.Parameters[i].Equals(b.Parameters[i]))
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using Microsoft.AspNetCore.App.Analyzers.Infrastructure;
using Microsoft.AspNetCore.Analyzers.RouteEmbeddedLanguage.Infrastructure;
using Microsoft.CodeAnalysis;
using WellKnownType = Microsoft.AspNetCore.App.Analyzers.Infrastructure.WellKnownTypeData.WellKnownType;

Expand All @@ -15,36 +16,50 @@ public EndpointParameter(IParameterSymbol parameter, WellKnownTypes wellKnownTyp
Type = parameter.Type;
Name = parameter.Name;
Source = EndpointParameterSource.Unknown;
HandlerArgument = $"{parameter.Name}_local";

if (GetSpecialTypeCallingCode(Type, wellKnownTypes) is string callingCode)
var fromQueryMetadataInterfaceType = wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Http_Metadata_IFromQueryMetadata);

if (GetSpecialTypeAssigningCode(Type, wellKnownTypes) is string assigningCode)
{
Source = EndpointParameterSource.SpecialType;
CallingCode = callingCode;
AssigningCode = assigningCode;
}
else if (parameter.HasAttributeImplementingInterface(fromQueryMetadataInterfaceType))
{
Source = EndpointParameterSource.Query;
AssigningCode = $"httpContext.Request.Query[\"{parameter.Name}\"]";
}
else
{
// TODO: Inferencing rules go here - but for now:
Source = EndpointParameterSource.Unknown;
}

if (parameter.Type is INamedTypeSymbol parameterType && parameterType.ContainingType?.SpecialType == SpecialType.System_Nullable_T)
{
IsOptional = true;
}

// TODO: Need to handle arrays (wrapped and unwrapped in nullable)!
}

public ITypeSymbol Type { get; }
public EndpointParameterSource Source { get; }

// TODO: If the parameter has [FromRoute("AnotherName")] or similar, prefer that.
public string Name { get; }
public string? CallingCode { get; }
public string? AssigningCode { get; }
public string HandlerArgument { get; }
public bool IsOptional { get; }

public string EmitArgument()
{
switch (Source)
{
case EndpointParameterSource.SpecialType:
return CallingCode!;
default:
// Eventually there should be know unknown parameter sources, but in the meantime we don't expect them to get this far.
// The netstandard2.0 target means there is no UnreachableException.
throw new Exception("Unreachable!");
}
return HandlerArgument;
}

// TODO: Handle special form types like IFormFileCollection that need special body-reading logic.
private static string? GetSpecialTypeCallingCode(ITypeSymbol type, WellKnownTypes wellKnownTypes)
private static string? GetSpecialTypeAssigningCode(ITypeSymbol type, WellKnownTypes wellKnownTypes)
{
if (SymbolEqualityComparer.Default.Equals(type, wellKnownTypes.Get(WellKnownType.Microsoft_AspNetCore_Http_HttpContext)))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Cache;
using System.Text;
using Microsoft.AspNetCore.Http.Generators.StaticRouteHandlerModel.Emitters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Microsoft.AspNetCore.Http.Generators.StaticRouteHandlerModel;

Expand Down Expand Up @@ -61,14 +65,18 @@ public static string EmitRequestHandler(this Endpoint endpoint)
var resultAssignment = endpoint.Response.IsVoid ? string.Empty : "var result = ";
var awaitHandler = endpoint.Response.IsAwaitable ? "await " : string.Empty;
var setContentType = endpoint.Response.IsVoid ? string.Empty : $@"httpContext.Response.ContentType ??= ""{endpoint.Response.ContentType}"";";
return $$"""
{{handlerSignature}}
{
{{setContentType}}
{{resultAssignment}}{{awaitHandler}}handler({{endpoint.EmitArgumentList()}});
{{(endpoint.Response.IsVoid ? "return Task.CompletedTask;" : endpoint.EmitResponseWritingCall())}}
}
""";

var requestHandlerSource = $$"""
{{handlerSignature}}
{
{{endpoint.EmitParameterPreparation()}}
{{setContentType}}
{{resultAssignment}}{{awaitHandler}}handler({{endpoint.EmitArgumentList()}});
{{(endpoint.Response.IsVoid ? "return Task.CompletedTask;" : endpoint.EmitResponseWritingCall())}}
}
""";

return requestHandlerSource;
}

private static string EmitResponseWritingCall(this Endpoint endpoint)
Expand Down Expand Up @@ -115,7 +123,8 @@ public static string EmitFilteredRequestHandler(this Endpoint endpoint)
return $$"""
async Task RequestHandlerFiltered(HttpContext httpContext)
{
var result = await filteredInvocation(new DefaultEndpointFilterInvocationContext(httpContext{{argumentList}}));
// var result = await filteredInvocation(new DefaultEndpointFilterInvocationContext(httpContext{{argumentList}}));
var result = await filteredInvocation(new DefaultEndpointFilterInvocationContext(httpContext));
await GeneratedRouteBuilderExtensionsCore.ExecuteObjectResult(result, httpContext);
}
""";
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<Reference Include="Microsoft.AspNetCore.Http" />
<Reference Include="Microsoft.AspNetCore.Http.Results" />
<Reference Include="Microsoft.AspNetCore.Http.Extensions" />
<Reference Include="Microsoft.AspNetCore.Mvc.Core" />
<Reference Include="Microsoft.CodeAnalysis.CSharp" />
<Reference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
<Reference Include="Microsoft.Extensions.DependencyInjection" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Microsoft.AspNetCore.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis;
using JsonOptions = Microsoft.AspNetCore.Http.Json.JsonOptions;

namespace Microsoft.AspNetCore.Http.Extensions.Tests;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Moq;
using JsonOptions = Microsoft.AspNetCore.Http.Json.JsonOptions;

namespace Microsoft.AspNetCore.Http.Extensions.Tests;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,16 @@ namespace Microsoft.AspNetCore.Http.Generated
handler.Method);
}

Task RequestHandler(HttpContext httpContext)
{
httpContext.Response.ContentType ??= "text/plain";
var result = handler();
return httpContext.Response.WriteAsync(result);
}
Task RequestHandler(HttpContext httpContext)
{

httpContext.Response.ContentType ??= "text/plain";
var result = handler();
return httpContext.Response.WriteAsync(result);
}
async Task RequestHandlerFiltered(HttpContext httpContext)
{
// var result = await filteredInvocation(new DefaultEndpointFilterInvocationContext(httpContext));
var result = await filteredInvocation(new DefaultEndpointFilterInvocationContext(httpContext));
await GeneratedRouteBuilderExtensionsCore.ExecuteObjectResult(result, httpContext);
}
Expand Down
Loading