Skip to content

Commit

Permalink
In SSR, supply HttpContext as cascading value (#50253)
Browse files Browse the repository at this point in the history
Fixes #48769

### Usage

```cs
[CascadingParameter] public HttpContext? Context { get; set; }
```

In SSR, this will receive the `HttpContext`. In other rendering modes where there is no HTTP context, no value will be supplied so the property will remain `null`.

### Alternative design considered

In #48769 I suggested using `[SupplyParameterFromHttpContext]` but that turns out not to be practical unless we either (a) make `ICascadingValueSupplier` public, or (b) add an IVT from `M.A.Components` to `.Endpoints`.

I'm not keen on doing either of the above on a whim. Plus, use of `[CascadingValue]` has advantages:

 * It's consistent with the existing pattern for authentication state (we have `[CascadingParameter] Task<AuthenticationState> AuthenticationStateTask { get; set; }`).
 * Longer term, if we add more things like this, it would be nice not to add a separate special attribute for each one when `[CascadingParameter]` is already descriptive enough. Special attributes are needed only when the type of thing being supplied might reasonably clash with something else the application is doing (for example, we do need it for form/query, as they supply arbitrary types).

## Review notes

It's best to look at the two commits in this PR completely separately:

1. The first commit fixes an API design problem I discovered while considering how to do this. I realised that when we added `CascadingParameterAttributeBase`, we made a design mistake:
   * We put the `Name` property on the abstract base class just because `CascadingParameterAttribute`, `SupplyParameterFromQuery`, and `SupplyParameterFromForm` all have a `Name`.
   * However, in all three cases there, the `Name` has completely different meanings. For `CascadingParameterAttribute`, it's the name associated with `<CascadingValue Name=...>`, whereas for form it's the `Request.Form` entry or fall back on property name, and for query it's the `Request.Query` entry or fall back on property name. In general there's no reason why a `CascadingParameterAttributeBase` subclass should have a `Name` at all (`SupplyParameterFromHttpContext` wasn't going to), and if it does have one, its semantics are specific to it. So these should not be the same properties.
   * The change we made to make `CascadingParameterAttribute.Name` virtual might even be breaking (see https://learn.microsoft.com/en-us/dotnet/core/compatibility/library-change-rules stating *DISALLOWED: Adding the virtual keyword to a member*). So it's good we can revert that here.
2. The second commit is the completely trivial implementation of supplying `HttpContext` as a cascading value, with an E2E test.
  • Loading branch information
SteveSandersonMS committed Aug 23, 2023
1 parent 61852ce commit 5ad966e
Show file tree
Hide file tree
Showing 19 changed files with 220 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ public sealed class CascadingParameterAttribute : CascadingParameterAttributeBas
/// <see cref="CascadingValue{T}"/> that supplies a value with a compatible
/// type.
/// </summary>
public override string? Name { get; set; }
public string? Name { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@ namespace Microsoft.AspNetCore.Components;
/// </summary>
public abstract class CascadingParameterAttributeBase : Attribute
{
/// <summary>
/// Gets or sets the name for the parameter, which correlates to the name
/// of a cascading value.
/// </summary>
public abstract string? Name { get; set; }

/// <summary>
/// Gets a flag indicating whether the cascading parameter should
/// be supplied only once per component.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection;

Expand Down Expand Up @@ -50,4 +51,59 @@ public static IServiceCollection AddCascadingValue<TValue>(
public static IServiceCollection AddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, CascadingValueSource<TValue>> sourceFactory)
=> serviceCollection.AddScoped<ICascadingValueSupplier>(sourceFactory);

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type. This is equivalent to having a fixed <see cref="CascadingValue{TValue}"/> at
/// the root of the component hierarchy.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="valueFactory">A callback that supplies a fixed value within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, TValue> valueFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(
sp => new CascadingValueSource<TValue>(() => valueFactory(sp), isFixed: true)));
}

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type, regardless of the <paramref name="name"/>. This is equivalent to having a fixed
/// <see cref="CascadingValue{TValue}"/> at the root of the component hierarchy.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="name">A name for the cascading value. If set, <see cref="CascadingParameterAttribute"/> can be configured to match based on this name.</param>
/// <param name="valueFactory">A callback that supplies a fixed value within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, string name, Func<IServiceProvider, TValue> valueFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(
sp => new CascadingValueSource<TValue>(name, () => valueFactory(sp), isFixed: true)));
}

/// <summary>
/// Adds a cascading value to the <paramref name="serviceCollection"/>, if none is already registered
/// with the value type. This is equivalent to having a fixed <see cref="CascadingValue{TValue}"/> at
/// the root of the component hierarchy.
///
/// With this overload, you can supply a <see cref="CascadingValueSource{TValue}"/> which allows you
/// to notify about updates to the value later, causing recipients to re-render. This overload should
/// only be used if you plan to update the value dynamically.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="sourceFactory">A callback that supplies a <see cref="CascadingValueSource{TValue}"/> within each service provider scope.</param>
/// <returns>The <see cref="IServiceCollection"/>.</returns>
public static void TryAddCascadingValue<TValue>(
this IServiceCollection serviceCollection, Func<IServiceProvider, CascadingValueSource<TValue>> sourceFactory)
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Scoped<ICascadingValueSupplier, CascadingValueSource<TValue>>(sourceFactory));
}
}
13 changes: 3 additions & 10 deletions src/Components/Components/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
#nullable enable
abstract Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.Name.get -> string?
abstract Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.Name.set -> void
abstract Microsoft.AspNetCore.Components.RenderModeAttribute.Mode.get -> Microsoft.AspNetCore.Components.IComponentRenderMode!
Microsoft.AspNetCore.Components.CascadingParameterAttributeBase
Microsoft.AspNetCore.Components.CascadingParameterAttributeBase.CascadingParameterAttributeBase() -> void
Expand Down Expand Up @@ -83,24 +81,19 @@ Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder.AddComponentParamete
Microsoft.AspNetCore.Components.StreamRenderingAttribute
Microsoft.AspNetCore.Components.StreamRenderingAttribute.Enabled.get -> bool
Microsoft.AspNetCore.Components.StreamRenderingAttribute.StreamRenderingAttribute(bool enabled) -> void
*REMOVED*Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.get -> string?
*REMOVED*Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.set -> void
Microsoft.AspNetCore.Components.SupplyParameterFromQueryProviderServiceCollectionExtensions
Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions
override Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.get -> string?
override Microsoft.AspNetCore.Components.CascadingParameterAttribute.Name.set -> void
override Microsoft.AspNetCore.Components.EventCallback.GetHashCode() -> int
override Microsoft.AspNetCore.Components.EventCallback.Equals(object? obj) -> bool
override Microsoft.AspNetCore.Components.EventCallback<TValue>.GetHashCode() -> int
override Microsoft.AspNetCore.Components.EventCallback<TValue>.Equals(object? obj) -> bool
*REMOVED*Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.get -> string?
*REMOVED*Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.set -> void
override Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.get -> string?
override Microsoft.AspNetCore.Components.SupplyParameterFromQueryAttribute.Name.set -> void
static Microsoft.AspNetCore.Components.SupplyParameterFromQueryProviderServiceCollectionExtensions.AddSupplyValueFromQueryProvider(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, string! name, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, Microsoft.AspNetCore.Components.CascadingValueSource<TValue>!>! sourceFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.AddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> Microsoft.Extensions.DependencyInjection.IServiceCollection!
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, string! name, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> void
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, Microsoft.AspNetCore.Components.CascadingValueSource<TValue>!>! sourceFactory) -> void
static Microsoft.Extensions.DependencyInjection.CascadingValueServiceCollectionExtensions.TryAddCascadingValue<TValue>(this Microsoft.Extensions.DependencyInjection.IServiceCollection! serviceCollection, System.Func<System.IServiceProvider!, TValue>! valueFactory) -> void
virtual Microsoft.AspNetCore.Components.NavigationManager.Refresh(bool forceReload = false) -> void
virtual Microsoft.AspNetCore.Components.Rendering.ComponentState.DisposeAsync() -> System.Threading.Tasks.ValueTask
virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.AddPendingTask(Microsoft.AspNetCore.Components.Rendering.ComponentState? componentState, System.Threading.Tasks.Task! task) -> void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,7 @@ private static void ThrowForUnknownIncomingParameterName([DynamicallyAccessedMem
{
throw new InvalidOperationException(
$"Object of type '{targetType.FullName}' has a property matching the name '{parameterName}', " +
$"but it does not have [{nameof(ParameterAttribute)}], [{nameof(CascadingParameterAttribute)}] or " +
$"[SupplyParameterFromFormAttribute] applied.");
$"but it does not have [Parameter], [CascadingParameter], or any other parameter-supplying attribute.");
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ public sealed class SupplyParameterFromQueryAttribute : CascadingParameterAttrib
/// Gets or sets the name of the querystring parameter. If null, the querystring
/// parameter is assumed to have the same name as the associated property.
/// </summary>
public override string? Name { get; set; }
public string? Name { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public bool CanSupplyValue(in CascadingParameterInfo parameterInfo)
UpdateQueryParameters();
}

var queryParameterName = parameterInfo.Attribute.Name ?? parameterInfo.PropertyName;
var attribute = (SupplyParameterFromQueryAttribute)parameterInfo.Attribute; // Must be a valid cast because we check in CanSupplyValue
var queryParameterName = attribute.Name ?? parameterInfo.PropertyName;
return _queryParameterValueSupplier.GetQueryParameterValue(parameterInfo.PropertyType, queryParameterName);
}

Expand Down
18 changes: 0 additions & 18 deletions src/Components/Components/test/CascadingParameterStateTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,6 @@ class ComponentWithNamedCascadingParam : TestComponentBase

class SupplyParameterWithSingleDeliveryAttribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }

internal override bool SingleDelivery => true;
}

Expand Down Expand Up @@ -523,19 +521,3 @@ public TestNavigationManager()
}
}
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class SupplyParameterFromFormAttribute : CascadingParameterAttributeBase
{
/// <summary>
/// Gets or sets the name for the parameter. The name is used to match
/// the form data and decide whether or not the value needs to be bound.
/// </summary>
public override string Name { get; set; }

/// <summary>
/// Gets or sets the name for the handler. The name is used to match
/// the form data and decide whether or not the value needs to be bound.
/// </summary>
public string Handler { get; set; }
}
56 changes: 50 additions & 6 deletions src/Components/Components/test/CascadingParameterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -727,15 +727,58 @@ public void OmitsSingleDeliveryCascadingParametersWhenUpdatingDirectParameters()
});
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_ValueFactory()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue(_ => new Type1());
services.TryAddCascadingValue(_ => new Type1());
services.TryAddCascadingValue(_ => new Type2());

// Assert
Assert.Equal(2, services.Count());
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_NamedValueFactory()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue("Name1", _ => new Type1());
services.TryAddCascadingValue("Name2", _ => new Type1());
services.TryAddCascadingValue("Name3", _ => new Type2());

// Assert
Assert.Equal(2, services.Count());
}

[Fact]
public void CanUseTryAddPatternForCascadingValuesInServiceCollection_CascadingValueSource()
{
// Arrange
var services = new ServiceCollection();

// Act
services.TryAddCascadingValue(_ => new CascadingValueSource<Type1>("Name1", new Type1(), false));
services.TryAddCascadingValue(_ => new CascadingValueSource<Type1>("Name2", new Type1(), false));
services.TryAddCascadingValue(_ => new CascadingValueSource<Type2>("Name3", new Type2(), false));

// Assert
Assert.Equal(2, services.Count());
}

private class SingleDeliveryValue(string text)
{
public string Text => text;
}

private class SingleDeliveryCascadingParameterAttribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }

internal override bool SingleDelivery => true;
}

Expand Down Expand Up @@ -852,13 +895,11 @@ class SecondCascadingParameterConsumerComponent<T1, T2> : CascadingParameterCons
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
class CustomCascadingParameter1Attribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
class CustomCascadingParameter2Attribute : CascadingParameterAttributeBase
{
public override string Name { get; set; }
}

class CustomCascadingValueProducer<TAttribute> : AutoRenderComponent, ICascadingValueSupplier
Expand Down Expand Up @@ -904,7 +945,7 @@ void ICascadingValueSupplier.Unsubscribe(ComponentState subscriber, in Cascading

class CustomCascadingValueConsumer1 : AutoRenderComponent
{
[CustomCascadingParameter1(Name = nameof(Value))]
[CustomCascadingParameter1]
public object Value { get; set; }

protected override void BuildRenderTree(RenderTreeBuilder builder)
Expand All @@ -915,7 +956,7 @@ protected override void BuildRenderTree(RenderTreeBuilder builder)

class CustomCascadingValueConsumer2 : AutoRenderComponent
{
[CustomCascadingParameter2(Name = nameof(Value))]
[CustomCascadingParameter2]
public object Value { get; set; }

protected override void BuildRenderTree(RenderTreeBuilder builder)
Expand Down Expand Up @@ -944,4 +985,7 @@ public void ChangeValue(string newValue)
StringValue = newValue;
}
}

class Type1 { }
class Type2 { }
}
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ public void IncomingParameterMatchesPropertyNotDeclaredAsParameter_Throws()
Assert.Equal(default, target.IntProp);
Assert.Equal(
$"Object of type '{typeof(HasPropertyWithoutParameterAttribute).FullName}' has a property matching the name '{nameof(HasPropertyWithoutParameterAttribute.IntProp)}', " +
$"but it does not have [{nameof(ParameterAttribute)}], [{nameof(CascadingParameterAttribute)}] or [{nameof(SupplyParameterFromFormAttribute)}] applied.",
"but it does not have [Parameter], [CascadingParameter], or any other parameter-supplying attribute.",
ex.Message);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection
services.TryAddScoped<EndpointRoutingStateProvider>();
services.TryAddScoped<IRoutingStateProvider>(sp => sp.GetRequiredService<EndpointRoutingStateProvider>());
services.AddSupplyValueFromQueryProvider();
services.TryAddCascadingValue(sp => sp.GetRequiredService<EndpointHtmlRenderer>().HttpContext);

// Form handling
services.AddSupplyValueFromFormProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ public EndpointHtmlRenderer(IServiceProvider serviceProvider, ILoggerFactory log
_services = serviceProvider;
}

internal HttpContext? HttpContext => _httpContext;

private void SetHttpContext(HttpContext httpContext)
{
if (_httpContext is null)
Expand Down
Loading

0 comments on commit 5ad966e

Please sign in to comment.