-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
Summary
Design proposal for Short circuit attribute. Change internal ShortCircuitMetadata to public ShortCircuitAttribute.
Motivation and goals
Currently, short circuit routing can only be used with the Minimal API. But many solutions are still based on controllers. Having an attribute would allow MVC actions to support short circuiting. Also, it would be useful for gRPC methods. More arguments in favor of the ShortCircuitAttribute can be found in the original issue.
This feature is very similar to Disabling HTTP metrics, where there is both an DisableHttpMetricsAttribute and an extension method DisableHttpMetrics for IEndpointConventionBuilder.
In scope
Any non-minimal endpoints.
Out of scope
None.
Risks / unknowns
None come to mind right now.
Examples
[ApiController]
[Route("[controller]")]
[ShortCircuit]
public class WeatherForecastController : ControllerBase
{
}[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
[ShortCircuit(200)]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}Detailed design
Now we have a ShortCircuitMetadata class:
internal sealed class ShortCircuitMetadata
{
public int? StatusCode { get; }
public ShortCircuitMetadata(int? statusCode)
{
StatusCode = statusCode;
}
}I suggest adding a new class ShortCircuitAttribute instead.
namespace Microsoft.AspNetCore.Routing;
/// <summary>
/// Short circuit the endpoint(s).
/// The execution of the endpoint will happen in UseRouting middleware.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
[DebuggerDisplay("{ToString(),nq}")]
public sealed class ShortCircuitAttribute : Attribute
{
/// <summary>
/// Constructs an instance of <see cref="ShortCircuitAttribute"/>.
/// </summary>
public ShortCircuitAttribute()
{
}
/// <summary>
/// Constructs an instance of <see cref="ShortCircuitAttribute"/>.
/// </summary>
/// <param name="statusCode">The status code to set in the response.</param>
public ShortCircuitAttribute(int statusCode)
{
StatusCode = statusCode;
}
/// <summary>
/// The status code to set in the response.
/// </summary>
public int? StatusCode { get; }
/// <inheritdoc/>
public override string ToString()
{
return "ShortCircuit";
}
}The new class is fully backward compatible with the old one, but allows it to be used as an attribute.