File size: 36,462 Bytes
d0faac4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | diff --git a/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs b/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs
new file mode 100644
index 00000000..815bf2c8
--- /dev/null
+++ b/src/Http/Http.Abstractions/src/Metadata/ApiEndpointMetadata.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace Microsoft.AspNetCore.Http.Metadata;
+
+/// <summary>
+/// Metadata that indicates the endpoint is intended for API clients.
+/// When present, authentication handlers should prefer returning status codes over browser redirects.
+/// </summary>
+internal sealed class ApiEndpointMetadata : IApiEndpointMetadata
+{
+ /// <summary>
+ /// Singleton instance of <see cref="ApiEndpointMetadata"/>.
+ /// </summary>
+ public static readonly ApiEndpointMetadata Instance = new();
+
+ private ApiEndpointMetadata()
+ {
+ }
+}
diff --git a/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs b/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs
new file mode 100644
index 00000000..cadaafca
--- /dev/null
+++ b/src/Http/Http.Abstractions/src/Metadata/IApiEndpointMetadata.cs
@@ -0,0 +1,12 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace Microsoft.AspNetCore.Http.Metadata;
+
+/// <summary>
+/// Metadata that indicates the endpoint is an API intended for programmatic access rather than direct browser navigation.
+/// When present, authentication handlers should prefer returning status codes over browser redirects.
+/// </summary>
+public interface IApiEndpointMetadata
+{
+}
diff --git a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj
index d383efa6..37e17a0f 100644
--- a/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj
+++ b/src/Http/Http.Abstractions/src/Microsoft.AspNetCore.Http.Abstractions.csproj
@@ -35,7 +35,6 @@ Microsoft.AspNetCore.Http.HttpResponse</Description>
</ItemGroup>
<ItemGroup>
- <InternalsVisibleTo Include="Microsoft.AspNetCore.Http.Abstractions.Microbenchmarks" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Http.Extensions" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Http.Results" />
</ItemGroup>
@@ -61,5 +60,6 @@ Microsoft.AspNetCore.Http.HttpResponse</Description>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Http.Abstractions.Tests" />
+ <InternalsVisibleTo Include="Microsoft.AspNetCore.Http.Abstractions.Microbenchmarks" />
</ItemGroup>
</Project>
diff --git a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt
index 3a246130..2944a853 100644
--- a/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt
+++ b/src/Http/Http.Abstractions/src/PublicAPI.Unshipped.txt
@@ -1,4 +1,5 @@
#nullable enable
+Microsoft.AspNetCore.Http.Metadata.IApiEndpointMetadata
Microsoft.AspNetCore.Http.Metadata.IDisableValidationMetadata
Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata.Description.get -> string?
Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata.Description.set -> void
diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs
index f4e2ad0e..f5e2abac 100644
--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs
+++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGenerator.cs
@@ -248,7 +248,12 @@ public sealed class RequestDelegateGenerator : IIncrementalGenerator
if (hasFormBody)
{
- codeWriter.WriteLine(RequestDelegateGeneratorSources.AntiforgeryMetadataType);
+ codeWriter.WriteLine(RequestDelegateGeneratorSources.AntiforgeryMetadataClass);
+ }
+
+ if (hasJsonBody || hasResponseMetadata)
+ {
+ codeWriter.WriteLine(RequestDelegateGeneratorSources.ApiEndpointMetadataClass);
}
if (hasFormBody || hasJsonBody || hasResponseMetadata)
diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs
index d7c7a480..b626db27 100644
--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs
+++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs
@@ -479,19 +479,39 @@ internal static class RequestDelegateGeneratorSources
}
""";
- public static string AntiforgeryMetadataType = """
-file sealed class AntiforgeryMetadata : IAntiforgeryMetadata
-{
- public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true);
-
- public AntiforgeryMetadata(bool requiresValidation)
+ public static string AntiforgeryMetadataClass = """
+ file sealed class AntiforgeryMetadata : IAntiforgeryMetadata
{
- RequiresValidation = requiresValidation;
+ public static readonly IAntiforgeryMetadata ValidationRequired = new AntiforgeryMetadata(true);
+
+ public AntiforgeryMetadata(bool requiresValidation)
+ {
+ RequiresValidation = requiresValidation;
+ }
+
+ public bool RequiresValidation { get; }
}
+""";
- public bool RequiresValidation { get; }
-}
+ public static string ApiEndpointMetadataClass = """
+ file sealed class ApiEndpointMetadata : IApiEndpointMetadata
+ {
+ public static readonly ApiEndpointMetadata Instance = new();
+
+ private ApiEndpointMetadata()
+ {
+ }
+
+ public static void AddApiEndpointMetadataIfMissing(EndpointBuilder builder)
+ {
+ if (!builder.Metadata.Any(m => m is IApiEndpointMetadata))
+ {
+ builder.Metadata.Add(Instance);
+ }
+ }
+ }
""";
+
public static string GetGeneratedRouteBuilderExtensionsSource(string endpoints, string helperMethods, string helperTypes, ImmutableHashSet<string> verbs) => $$"""
{{SourceHeader}}
diff --git a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs
index 83790d44..97fe2dc9 100644
--- a/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs
+++ b/src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/StaticRouteHandlerModel/StaticRouteHandlerModel.Emitter.cs
@@ -205,7 +205,7 @@ internal static class StaticRouteHandlerModelEmitter
return;
}
- if (!endpoint.Response.IsAwaitable && (response.HasNoResponse || response.IsIResult))
+ if (response.HasNoResponse || response.IsIResult)
{
return;
}
@@ -215,13 +215,10 @@ internal static class StaticRouteHandlerModelEmitter
{
codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(string), contentTypes: GeneratedMetadataConstants.PlaintextContentType));");
}
- else if (response.IsAwaitable && response.ResponseType == null)
- {
- codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof(void), contentTypes: GeneratedMetadataConstants.PlaintextContentType));");
- }
else if (response.ResponseType is { } responseType)
{
codeWriter.WriteLine($$"""options.EndpointBuilder.Metadata.Add(new ProducesResponseTypeMetadata(statusCode: StatusCodes.Status200OK, type: typeof({{responseType.ToDisplayString(EmitterConstants.DisplayFormatWithoutNullability)}}), contentTypes: GeneratedMetadataConstants.JsonContentType));""");
+ codeWriter.WriteLine("ApiEndpointMetadata.AddApiEndpointMetadataIfMissing(options.EndpointBuilder);");
}
}
@@ -339,13 +336,15 @@ internal static class StaticRouteHandlerModelEmitter
codeWriter.WriteLine("if (!serviceProviderIsService.IsService(type))");
codeWriter.StartBlock();
codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(type: type, isOptional: isOptional, contentTypes: GeneratedMetadataConstants.JsonContentType));");
+ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance);");
codeWriter.WriteLine("break;");
codeWriter.EndBlock();
codeWriter.EndBlock();
}
else
{
- codeWriter.WriteLine($"options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType));");
+ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(new AcceptsMetadata(contentTypes: GeneratedMetadataConstants.JsonContentType));");
+ codeWriter.WriteLine("options.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance);");
}
}
diff --git a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs
index 19965ef1..aaebe417 100644
--- a/src/Http/Http.Extensions/src/RequestDelegateFactory.cs
+++ b/src/Http/Http.Extensions/src/RequestDelegateFactory.cs
@@ -401,7 +401,14 @@ public static partial class RequestDelegateFactory
InferAntiforgeryMetadata(factoryContext);
}
- PopulateBuiltInResponseTypeMetadata(methodInfo.ReturnType, factoryContext.EndpointBuilder);
+ // If this endpoint expects a JSON request body, we assume its an API endpoint not intended for browser navigation.
+ // When present, authentication handlers should prefer returning status codes over browser redirects.
+ if (factoryContext.JsonRequestBodyParameter is not null)
+ {
+ factoryContext.EndpointBuilder.Metadata.Add(ApiEndpointMetadata.Instance);
+ }
+
+ PopulateBuiltInResponseTypeMetadata(methodInfo.ReturnType, factoryContext);
// Add metadata provided by the delegate return type and parameter types next, this will be more specific than inferred metadata from above
EndpointMetadataPopulator.PopulateMetadata(methodInfo, factoryContext.EndpointBuilder, factoryContext.Parameters);
@@ -1023,37 +1030,40 @@ public static partial class RequestDelegateFactory
return Expression.Block(localVariables, checkParamAndCallMethod);
}
- private static void PopulateBuiltInResponseTypeMetadata(Type returnType, EndpointBuilder builder)
+ private static void PopulateBuiltInResponseTypeMetadata(Type returnType, RequestDelegateFactoryContext factoryContext)
{
if (returnType.IsByRefLike)
{
throw GetUnsupportedReturnTypeException(returnType);
}
- var isAwaitable = false;
if (CoercedAwaitableInfo.IsTypeAwaitable(returnType, out var coercedAwaitableInfo))
{
returnType = coercedAwaitableInfo.AwaitableInfo.ResultType;
- isAwaitable = true;
}
// Skip void returns and IResults. IResults might implement IEndpointMetadataProvider but otherwise we don't know what it might do.
- if (!isAwaitable && (returnType == typeof(void) || typeof(IResult).IsAssignableFrom(returnType)))
+ if (returnType == typeof(void) || typeof(IResult).IsAssignableFrom(returnType))
{
return;
}
+ var builder = factoryContext.EndpointBuilder;
+
if (returnType == typeof(string))
{
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(type: typeof(string), statusCode: 200, PlaintextContentType));
}
- else if (returnType == typeof(void))
- {
- builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(returnType, statusCode: 200, PlaintextContentType));
- }
else
{
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(returnType, statusCode: 200, DefaultAcceptsAndProducesContentType));
+
+ if (factoryContext.JsonRequestBodyParameter is null)
+ {
+ // Since this endpoint responds with JSON, we assume its an API endpoint not intended for browser navigation,
+ // but we don't want to bother adding this metadata twice if we've already inferred it based on the expected JSON request body.
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
+ }
}
}
diff --git a/src/Http/Http.Results/src/Accepted.cs b/src/Http/Http.Results/src/Accepted.cs
index 5dbc5698..d71fe907 100644
--- a/src/Http/Http.Results/src/Accepted.cs
+++ b/src/Http/Http.Results/src/Accepted.cs
@@ -82,5 +82,6 @@ public sealed class Accepted : IResult, IEndpointMetadataProvider, IStatusCodeHt
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/AcceptedAtRoute.cs b/src/Http/Http.Results/src/AcceptedAtRoute.cs
index 74725595..900ee507 100644
--- a/src/Http/Http.Results/src/AcceptedAtRoute.cs
+++ b/src/Http/Http.Results/src/AcceptedAtRoute.cs
@@ -109,5 +109,6 @@ public sealed class AcceptedAtRoute : IResult, IEndpointMetadataProvider, IStatu
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs b/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs
index e9467dbe..b8e4304a 100644
--- a/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs
+++ b/src/Http/Http.Results/src/AcceptedAtRouteOfT.cs
@@ -123,5 +123,6 @@ public sealed class AcceptedAtRoute<TValue> : IResult, IEndpointMetadataProvider
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status202Accepted, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/AcceptedOfT.cs b/src/Http/Http.Results/src/AcceptedOfT.cs
index 6777d354..34607071 100644
--- a/src/Http/Http.Results/src/AcceptedOfT.cs
+++ b/src/Http/Http.Results/src/AcceptedOfT.cs
@@ -101,5 +101,6 @@ public sealed class Accepted<TValue> : IResult, IEndpointMetadataProvider, IStat
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status202Accepted, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/BadRequest.cs b/src/Http/Http.Results/src/BadRequest.cs
index 9eef74aa..0356afed 100644
--- a/src/Http/Http.Results/src/BadRequest.cs
+++ b/src/Http/Http.Results/src/BadRequest.cs
@@ -52,5 +52,6 @@ public sealed class BadRequest : IResult, IEndpointMetadataProvider, IStatusCode
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status400BadRequest, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/BadRequestOfT.cs b/src/Http/Http.Results/src/BadRequestOfT.cs
index 4b932786..b8fa5142 100644
--- a/src/Http/Http.Results/src/BadRequestOfT.cs
+++ b/src/Http/Http.Results/src/BadRequestOfT.cs
@@ -66,5 +66,6 @@ public sealed class BadRequest<TValue> : IResult, IEndpointMetadataProvider, ISt
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status400BadRequest, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/Conflict.cs b/src/Http/Http.Results/src/Conflict.cs
index da162ed5..f0067ba4 100644
--- a/src/Http/Http.Results/src/Conflict.cs
+++ b/src/Http/Http.Results/src/Conflict.cs
@@ -52,5 +52,6 @@ public sealed class Conflict : IResult, IEndpointMetadataProvider, IStatusCodeHt
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status409Conflict, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/ConflictOfT.cs b/src/Http/Http.Results/src/ConflictOfT.cs
index bbfb3c6a..dda54d9d 100644
--- a/src/Http/Http.Results/src/ConflictOfT.cs
+++ b/src/Http/Http.Results/src/ConflictOfT.cs
@@ -66,5 +66,6 @@ public sealed class Conflict<TValue> : IResult, IEndpointMetadataProvider, IStat
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status409Conflict, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/Created.cs b/src/Http/Http.Results/src/Created.cs
index 7766d91a..19595562 100644
--- a/src/Http/Http.Results/src/Created.cs
+++ b/src/Http/Http.Results/src/Created.cs
@@ -82,5 +82,6 @@ public sealed class Created : IResult, IEndpointMetadataProvider, IStatusCodeHtt
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/CreatedAtRoute.cs b/src/Http/Http.Results/src/CreatedAtRoute.cs
index 2fb70fa2..2ff79596 100644
--- a/src/Http/Http.Results/src/CreatedAtRoute.cs
+++ b/src/Http/Http.Results/src/CreatedAtRoute.cs
@@ -109,5 +109,6 @@ public sealed class CreatedAtRoute : IResult, IEndpointMetadataProvider, IStatus
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status201Created, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/CreatedAtRouteOfT.cs b/src/Http/Http.Results/src/CreatedAtRouteOfT.cs
index d13d6154..a2868afd 100644
--- a/src/Http/Http.Results/src/CreatedAtRouteOfT.cs
+++ b/src/Http/Http.Results/src/CreatedAtRouteOfT.cs
@@ -126,5 +126,6 @@ public sealed class CreatedAtRoute<TValue> : IResult, IEndpointMetadataProvider,
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status201Created, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/CreatedOfT.cs b/src/Http/Http.Results/src/CreatedOfT.cs
index 58d0638b..a12e52b9 100644
--- a/src/Http/Http.Results/src/CreatedOfT.cs
+++ b/src/Http/Http.Results/src/CreatedOfT.cs
@@ -100,5 +100,6 @@ public sealed class Created<TValue> : IResult, IEndpointMetadataProvider, IStatu
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status201Created, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/InternalServerErrorOfT.cs b/src/Http/Http.Results/src/InternalServerErrorOfT.cs
index 36ec9fed..c726debf 100644
--- a/src/Http/Http.Results/src/InternalServerErrorOfT.cs
+++ b/src/Http/Http.Results/src/InternalServerErrorOfT.cs
@@ -66,5 +66,6 @@ public sealed class InternalServerError<TValue> : IResult, IEndpointMetadataProv
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status500InternalServerError, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/JsonHttpResultOfT.cs b/src/Http/Http.Results/src/JsonHttpResultOfT.cs
index 4841e675..fea23060 100644
--- a/src/Http/Http.Results/src/JsonHttpResultOfT.cs
+++ b/src/Http/Http.Results/src/JsonHttpResultOfT.cs
@@ -2,8 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
+using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -13,7 +16,7 @@ namespace Microsoft.AspNetCore.Http.HttpResults;
/// <summary>
/// An action result which formats the given object as JSON.
/// </summary>
-public sealed partial class JsonHttpResult<TValue> : IResult, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult<TValue>, IContentTypeHttpResult
+public sealed partial class JsonHttpResult<TValue> : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult<TValue>, IContentTypeHttpResult
{
/// <summary>
/// Initializes a new instance of the <see cref="Json"/> class with the values.
@@ -117,7 +120,7 @@ public sealed partial class JsonHttpResult<TValue> : IResult, IStatusCodeHttpRes
typedJsonTypeInfo,
contentType: ContentType);
}
-
+
return httpContext.Response.WriteAsJsonAsync(
Value,
JsonTypeInfo,
@@ -131,4 +134,9 @@ public sealed partial class JsonHttpResult<TValue> : IResult, IStatusCodeHttpRes
ContentType,
JsonSerializerOptions);
}
+
+ static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder)
+ {
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
+ }
}
diff --git a/src/Http/Http.Results/src/NoContent.cs b/src/Http/Http.Results/src/NoContent.cs
index 987a06fc..35ffb3c5 100644
--- a/src/Http/Http.Results/src/NoContent.cs
+++ b/src/Http/Http.Results/src/NoContent.cs
@@ -52,5 +52,6 @@ public class NoContent : IResult, IEndpointMetadataProvider, IStatusCodeHttpResu
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status204NoContent, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/NotFoundOfT.cs b/src/Http/Http.Results/src/NotFoundOfT.cs
index ad9c3a10..d37a4ee9 100644
--- a/src/Http/Http.Results/src/NotFoundOfT.cs
+++ b/src/Http/Http.Results/src/NotFoundOfT.cs
@@ -65,5 +65,6 @@ public sealed class NotFound<TValue> : IResult, IEndpointMetadataProvider, IStat
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status404NotFound, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/Ok.cs b/src/Http/Http.Results/src/Ok.cs
index 0db060d4..837a0fa7 100644
--- a/src/Http/Http.Results/src/Ok.cs
+++ b/src/Http/Http.Results/src/Ok.cs
@@ -51,5 +51,6 @@ public sealed class Ok : IResult, IEndpointMetadataProvider, IStatusCodeHttpResu
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/OkOfT.cs b/src/Http/Http.Results/src/OkOfT.cs
index 108674fd..7f19598e 100644
--- a/src/Http/Http.Results/src/OkOfT.cs
+++ b/src/Http/Http.Results/src/OkOfT.cs
@@ -65,5 +65,6 @@ public sealed class Ok<TValue> : IResult, IEndpointMetadataProvider, IStatusCode
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status200OK, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/ProblemHttpResult.cs b/src/Http/Http.Results/src/ProblemHttpResult.cs
index 4fe63c42..8ac29336 100644
--- a/src/Http/Http.Results/src/ProblemHttpResult.cs
+++ b/src/Http/Http.Results/src/ProblemHttpResult.cs
@@ -4,6 +4,9 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
+using System.Reflection;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http.Metadata;
namespace Microsoft.AspNetCore.Http.HttpResults;
@@ -11,7 +14,7 @@ namespace Microsoft.AspNetCore.Http.HttpResults;
/// An <see cref="IResult"/> that on execution will write Problem Details
/// HTTP API responses based on <see href="https://tools.ietf.org/html/rfc7807"/>
/// </summary>
-public sealed class ProblemHttpResult : IResult, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult<ProblemDetails>
+public sealed class ProblemHttpResult : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult<ProblemDetails>
{
/// <summary>
/// Creates a new <see cref="ProblemHttpResult"/> instance with
@@ -69,4 +72,13 @@ public sealed class ProblemHttpResult : IResult, IStatusCodeHttpResult, IContent
ContentType);
}
}
+
+ /// <inheritdoc/>
+ static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder)
+ {
+ ArgumentNullException.ThrowIfNull(method);
+ ArgumentNullException.ThrowIfNull(builder);
+
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
+ }
}
diff --git a/src/Http/Http.Results/src/ServerSentEventsResult.cs b/src/Http/Http.Results/src/ServerSentEventsResult.cs
index 448b2076..a7951acd 100644
--- a/src/Http/Http.Results/src/ServerSentEventsResult.cs
+++ b/src/Http/Http.Results/src/ServerSentEventsResult.cs
@@ -105,5 +105,6 @@ public sealed class ServerSentEventsResult<T> : IResult, IEndpointMetadataProvid
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(SseItem<T>), contentTypes: ["text/event-stream"]));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/UnprocessableEntity.cs b/src/Http/Http.Results/src/UnprocessableEntity.cs
index eef96dc9..49d39827 100644
--- a/src/Http/Http.Results/src/UnprocessableEntity.cs
+++ b/src/Http/Http.Results/src/UnprocessableEntity.cs
@@ -52,5 +52,6 @@ public sealed class UnprocessableEntity : IResult, IEndpointMetadataProvider, IS
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status422UnprocessableEntity, typeof(void)));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/UnprocessableEntityOfT.cs b/src/Http/Http.Results/src/UnprocessableEntityOfT.cs
index 475a0bc3..2d1ee494 100644
--- a/src/Http/Http.Results/src/UnprocessableEntityOfT.cs
+++ b/src/Http/Http.Results/src/UnprocessableEntityOfT.cs
@@ -66,5 +66,6 @@ public sealed class UnprocessableEntity<TValue> : IResult, IEndpointMetadataProv
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(TValue), StatusCodes.Status422UnprocessableEntity, ContentTypeConstants.ApplicationJsonContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Http/Http.Results/src/ValidationProblem.cs b/src/Http/Http.Results/src/ValidationProblem.cs
index ba738cfb..c4a539c9 100644
--- a/src/Http/Http.Results/src/ValidationProblem.cs
+++ b/src/Http/Http.Results/src/ValidationProblem.cs
@@ -77,5 +77,6 @@ public sealed class ValidationProblem : IResult, IEndpointMetadataProvider, ISta
ArgumentNullException.ThrowIfNull(builder);
builder.Metadata.Add(ProducesResponseTypeMetadata.CreateUnvalidated(typeof(HttpValidationProblemDetails), StatusCodes.Status400BadRequest, ContentTypeConstants.ProblemDetailsContentTypes));
+ builder.Metadata.Add(ApiEndpointMetadata.Instance);
}
}
diff --git a/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs b/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs
index 89d45efc..2f25045d 100644
--- a/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs
+++ b/src/Mvc/Mvc.ApiExplorer/src/EndpointMetadataApiDescriptionProvider.cs
@@ -332,10 +332,9 @@ internal sealed class EndpointMetadataApiDescriptionProvider : IApiDescriptionPr
var defaultErrorType = errorMetadata?.Type ?? typeof(void);
var contentTypes = new MediaTypeCollection();
- // If the return type is an IResult or an awaitable IResult, then we should treat it as a void return type
- // since we can't infer anything without additional metadata.
- if (typeof(IResult).IsAssignableFrom(responseType) ||
- producesResponseMetadata.Any(metadata => typeof(IResult).IsAssignableFrom(metadata.Type)))
+ // If the return type is an IResult or wrapped in a Task or ValueTask, then we should treat it as a void return type
+ // since we can't infer anything without additional metadata or requiring unreferenced code.
+ if (IsTaskOrValueTask(responseType) || typeof(IResult).IsAssignableFrom(responseType))
{
responseType = typeof(void);
}
@@ -427,6 +426,23 @@ internal sealed class EndpointMetadataApiDescriptionProvider : IApiDescriptionPr
return apiResponseType == metadataType ||
metadataType?.IsAssignableFrom(apiResponseType) == true;
}
+
+ static bool IsTaskOrValueTask(Type returnType)
+ {
+ // If this method did not need to be trim-safe, we would use CoercedAwaitableInfo.IsTypeAwaitable, but we cannot.
+ if (returnType.IsAssignableFrom(typeof(Task)) || returnType.IsAssignableFrom(typeof(ValueTask)))
+ {
+ return true;
+ }
+
+ if (returnType.FullName is null)
+ {
+ return false;
+ }
+
+ return returnType.FullName.StartsWith("System.Threading.Tasks.Task`1[", StringComparison.Ordinal) ||
+ returnType.FullName.StartsWith("System.Threading.Tasks.ValueTask`1[", StringComparison.Ordinal);
+ }
}
private static ApiResponseType CreateDefaultApiResponseType(Type responseType)
diff --git a/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs b/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs
index a1b95b3e..f7179b0b 100644
--- a/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs
+++ b/src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs
@@ -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 Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace Microsoft.AspNetCore.Mvc;
@@ -17,6 +18,6 @@ namespace Microsoft.AspNetCore.Mvc;
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
-public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata
+public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata, IApiEndpointMetadata
{
}
diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs
index be47982a..994d999a 100644
--- a/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs
+++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Authentication.Cookies;
@@ -41,7 +42,7 @@ public class CookieAuthenticationEvents
/// </summary>
public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToLogin { get; set; } = context =>
{
- if (IsAjaxRequest(context.Request))
+ if (IsAjaxRequest(context.Request) || IsApiEndpoint(context.HttpContext))
{
context.Response.Headers.Location = context.RedirectUri;
context.Response.StatusCode = 401;
@@ -58,7 +59,7 @@ public class CookieAuthenticationEvents
/// </summary>
public Func<RedirectContext<CookieAuthenticationOptions>, Task> OnRedirectToAccessDenied { get; set; } = context =>
{
- if (IsAjaxRequest(context.Request))
+ if (IsAjaxRequest(context.Request) || IsApiEndpoint(context.HttpContext))
{
context.Response.Headers.Location = context.RedirectUri;
context.Response.StatusCode = 403;
@@ -108,6 +109,12 @@ public class CookieAuthenticationEvents
string.Equals(request.Headers.XRequestedWith, "XMLHttpRequest", StringComparison.Ordinal);
}
+ private static bool IsApiEndpoint(HttpContext context)
+ {
+ var endpoint = context.GetEndpoint();
+ return endpoint?.Metadata.GetMetadata<IApiEndpointMetadata>() is not null;
+ }
+
/// <summary>
/// Invoked to validate the principal.
/// </summary>
diff --git a/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs b/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs
index 8ed01395..f1aad864 100644
--- a/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs
+++ b/src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs
@@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Http.Connections.Internal;
+using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Http.Timeouts;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
@@ -125,6 +126,9 @@ public static class ConnectionEndpointRouteBuilderExtensions
{
e.Metadata.Add(data);
}
+
+ // Add IApiEndpointMetadata to indicate this is a non-browser endpoint (SignalR)
+ e.Metadata.Add(ApiEndpointMetadata.Instance);
});
return new ConnectionEndpointRouteBuilder(compositeConventionBuilder);
@@ -155,4 +159,9 @@ public static class ConnectionEndpointRouteBuilderExtensions
}
}
}
+
+ private sealed class ApiEndpointMetadata : IApiEndpointMetadata
+ {
+ public static ApiEndpointMetadata Instance { get; } = new();
+ }
}
|