Skip to content

Fix: Detect parsability when FromRoute attribute is used #45597

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

Conversation

mitchdenny
Copy link
Member

@mitchdenny mitchdenny commented Dec 15, 2022

…aming.

Detect parsability even when FromRoute attribute is used to map handler parameters to route parameters.

There was a bug in my recent analyzer change where the following wouldn't produce an error:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
var webApp = WebApplication.Create();
webApp.MapGet("/customers/{cust}", ([FromRoute(Name = "cust")]Customer customer) => {});

public class Customer {}

It should however warn that Customer type is not parsable.

Description

To fix I introduced some logic to resolve the route parameter name if the FromRoute attribute is present. If it is it uses that instead to determine whether to apply the analyzer error. Arguably I could key just off the presence of the [FromRoute] attribute and not drill into the name, but I think we would want to avoid providing this analyzer error in that case and allow another analyzer to warn on a mismatch between route parameters and handler parameters.

Fixes #45581

@ghost ghost added the area-infrastructure Includes: MSBuild projects/targets, build scripts, CI, Installers and shared framework label Dec 15, 2022
@mitchdenny mitchdenny self-assigned this Dec 15, 2022
@mitchdenny mitchdenny requested a review from JamesNK December 15, 2022 03:09
@JamesNK
Copy link
Member

JamesNK commented Dec 15, 2022

What happens if you do this?

webApp.MapGet("/customers/{cust}", ([FromRoute(Name = "cust")]Customer customer, string cust) => {});

I'm guessing it explodes at runtime. What happens in the parsability analyzer? (we could write an analyzer that detects this situation and warns about it, but it probably wouldn't get much usage)

@JamesNK
Copy link
Member

JamesNK commented Dec 15, 2022

Good find btw. I need to consider using FromRoute.Name in some of the tooling I've written recently.

@mitchdenny
Copy link
Member Author

I'm guessing it explodes at runtime.

Oh interesting. It doesn't throw - it actually works. The route parameter value gets put into the string and TryParse gets called. I'm not entirely sure that this should be considered an error. For example the following is also considered valid:

app.MapGet("/customers/{cust}", ([FromRoute(Name = "cust")] Customer aaa, [FromRoute(Name = "cust")] Customer customer, string cust) => {});

@JamesNK
Copy link
Member

JamesNK commented Dec 21, 2022

I guess there isn't anything wrong with multiple arguments binding to the same route value.

Copy link
Member

@JamesNK JamesNK left a comment

Choose a reason for hiding this comment

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

LGTM

It would be good to add a unit test of multiple arguments binding to one parameter, just to verify that it doesn't break the analyzer. Maybe a comment to the code as well that it doesn't matter if multiple parameters have the same name.

@JamesNK
Copy link
Member

JamesNK commented Dec 22, 2022

Fixes in various bits of route tooling for this issue: #45720

My PR adds the resolved parameter name to route usage information. I reused and centralized what you did in this PR. It should be possible to simplify this PR by reusing it.

@mitchdenny
Copy link
Member Author

It should be possible to simplify this PR by reusing it.

Will pick this up after the holidays and integrate your changes (assuming they are merged by then).

@mitchdenny mitchdenny force-pushed the 45581-handle-fromroute-attributes-with-overridden-names branch from 0595940 to 7cbe4b3 Compare December 23, 2022 04:51
@mitchdenny mitchdenny force-pushed the 45581-handle-fromroute-attributes-with-overridden-names branch from 06ece9a to a6a69a8 Compare January 2, 2023 23:56
@mitchdenny mitchdenny requested a review from JamesNK January 3, 2023 00:41
@mitchdenny
Copy link
Member Author

@JamesNK I integrated your changes into my PR. It involved moving the SymbolExtensions type into a more common location since we use it outside of the pattern analyzer stuff now as well. I also hoisted the ResolveParameterName(...) method into a RouteParameterHelper class so it can be reused (this is because my logic actually loops over the delegate handler parameters - not the route pattern itself).

Wanted to give you a final chance to review before I squash and merge.

@JamesNK
Copy link
Member

JamesNK commented Jan 3, 2023

I made a collection of resolved parameters available from RouteUsageModel:

// RouteParameterName can be different from parameter name using FromRouteAttribute. e.g. [FromRoute(Name = "custom_name")]
internal record struct ParameterSymbol(string RouteParameterName, ISymbol Symbol, ISymbol? TopLevelSymbol = null)
{
public bool IsNested => TopLevelSymbol != null;
}
internal readonly record struct RouteUsageContext(
IMethodSymbol? MethodSymbol,
SyntaxNode? MethodSyntax,
RouteUsageType UsageType,
ImmutableArray<ISymbol> Parameters,
ImmutableArray<ParameterSymbol> ResolvedParameters)
{
public RoutePatternOptions RoutePatternOptions => UsageType switch
{
RouteUsageType.MvcAction or RouteUsageType.MvcController => RoutePatternOptions.MvcAttributeRoute,
RouteUsageType.Component => RoutePatternOptions.ComponentsRoute,
_ => RoutePatternOptions.DefaultRoute,
};
}

RouteParameterName uses the attribute to update the route name if needed. Could you pull the information you need from it? e.g. loop through the parameter collection, match on the symbol, then use RouteParameterName

@mitchdenny
Copy link
Member Author

mitchdenny commented Jan 3, 2023

Could you pull the information you need from it? e.g. loop through the parameter collection, match on the symbol, then use RouteParameterName

Are you suggesting something like this:

            var parameterSymbol = routeUsage.UsageContext.ResolvedParameters.FirstOrDefault(p => p.Symbol == (ISymbol)handlerDelegateParameter);
            var routeParameterName = parameterSymbol.RouteParameterName ?? handlerDelegateParameter.Name;

            // Match handler parameter against route parameters. If it is a route parameter it needs to be parsable/bindable in some fashion.
            if (routeUsage.RoutePattern.TryGetRouteParameter(routeParameterName, out var routeParameter))
            {
              ...

If that is the case, it doesn't seem to work. I can never get p.Symbol to match handlerDelegateParameter - which doesn't make sense to me they should be the same object instance right?

... I guess I can just resolve on symbol name in this particular case, but it's troubling that these objects don't ==.

@mitchdenny mitchdenny merged commit 09b0db0 into dotnet:main Jan 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-infrastructure Includes: MSBuild projects/targets, build scripts, CI, Installers and shared framework
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Route parameter TryParse checks does not handle handler parameters with [FromRoute] attribute where name is provided.
2 participants