@@ -6,6 +6,7 @@ namespace SqlStreamStore.HAL
66 using System . Threading . Tasks ;
77 using Microsoft . AspNetCore . Builder ;
88 using Microsoft . AspNetCore . Http ;
9+ using Microsoft . Extensions . Primitives ;
910 using MidFunc = System . Func <
1011 Microsoft . AspNetCore . Http . HttpContext ,
1112 System . Func < System . Threading . Tasks . Task > ,
@@ -20,37 +21,55 @@ public static IApplicationBuilder MapWhen(
2021 Action < IApplicationBuilder > configure ) => builder . MapWhen (
2122 context => string . Equals (
2223 context . Request . Method ,
23- method . ToString ( ) ,
24+ method . Method ,
2425 StringComparison . OrdinalIgnoreCase ) ,
2526 configure ) ;
2627
27- public static IApplicationBuilder UseAllowedMethods < TResource > ( this IApplicationBuilder builder , TResource resource )
28- where TResource : IResource
28+ public static IApplicationBuilder UseAllowedMethods ( this IApplicationBuilder builder , IResource resource )
2929 {
30- var allowed = ResourceMethods . Discover < TResource > ( ) ;
30+ var allowed = ResourceMethods . Discover ( resource ) ;
31+
32+ var allowedMethodsHeaderValue = allowed . Aggregate (
33+ StringValues . Empty ,
34+ ( previous , method ) => StringValues . Concat ( previous , method . Method ) ) ;
35+
36+ var allowedHeadersHeaderValue = new StringValues ( new [ ]
37+ {
38+ Constants . Headers . ContentType ,
39+ Constants . Headers . XRequestedWith ,
40+ Constants . Headers . Authorization
41+ } ) ;
42+
43+ Task Options ( HttpContext context , Func < Task > next )
44+ {
45+ context . Response . Headers . Append (
46+ Constants . Headers . AccessControl . AllowMethods ,
47+ allowedMethodsHeaderValue ) ;
48+ context . Response . Headers . Append (
49+ Constants . Headers . AccessControl . AllowHeaders ,
50+ allowedHeadersHeaderValue ) ;
51+ context . Response . Headers . Append (
52+ Constants . Headers . AccessControl . AllowOrigin ,
53+ "*" ) ;
54+
55+ return Task . CompletedTask ;
56+ }
3157
3258 Task AllowedMethods ( HttpContext context , Func < Task > next )
3359 {
3460 if ( ! allowed . Contains ( new HttpMethod ( context . Request . Method ) ) )
3561 {
3662 context . Response . StatusCode = 405 ;
63+ context . Response . Headers . Add ( Constants . Headers . Allowed , allowedMethodsHeaderValue ) ;
3764 return Task . CompletedTask ;
3865 }
3966
4067 return next ( ) ;
4168 }
4269
43-
4470 return builder
45- . Use ( Options ( allowed ) )
71+ . MapWhen ( HttpMethod . Options , inner => inner . Use ( Options ) )
4672 . Use ( AllowedMethods ) ;
4773 }
48-
49- private static MidFunc Options ( HttpMethod [ ] allowed ) => ( context , next ) =>
50- {
51- context . SetStandardCorsHeaders ( allowed ) ;
52-
53- return Task . CompletedTask ;
54- } ;
5574 }
5675}
0 commit comments