5 people like it.
Like the snippet!
Web API AsyncApiActionInvoker
Overrides the standard Web API ApiControllerActionInvoker with one that works with controller actions return F# Async<'T> results.
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:
|
open System
open System.Diagnostics.Contracts
open System.Net
open System.Net.Http
open System.Reflection
open System.Web.Http
open System.Web.Http.Controllers
type AsyncApiActionInvoker() =
inherit Controllers.ApiControllerActionInvoker()
let (|Async|_|) (ty: Type) =
if ty.IsGenericType && ty.GetGenericTypeDefinition() = typedefof<Async<_>> then
Some (ty.GetGenericArguments().[0])
else None
static let asTaskMethod = typeof<AsyncApiActionInvoker>.GetMethod("StartAsTask", BindingFlags.NonPublic ||| BindingFlags.Static)
static let voidResultConverter = VoidResultConverter()
static member internal GetResultConverter<'T>(actionContext: HttpActionContext) : IActionResultConverter =
let instanceType = typeof<'T>
if instanceType <> null && instanceType.IsGenericParameter then
raise <| InvalidOperationException()
if instanceType = null || typeof<HttpResponseMessage>.IsAssignableFrom instanceType then
// TODO: Verify Async<unit> passes through here.
actionContext.ActionDescriptor.ResultConverter
elif instanceType = typeof<unit> then
voidResultConverter :> _
else new ValueResultConverter<'T>() :> _
static member internal StartAsTask<'T>(actionContext: HttpActionContext, cancellationToken) =
let resultConverter = AsyncApiActionInvoker.GetResultConverter<'T>(actionContext)
let computation = async {
let task =
actionContext.ActionDescriptor.ExecuteAsync(
actionContext.ControllerContext,
actionContext.ActionArguments,
cancellationToken)
let! result = Async.AwaitTask task
let! (value: 'T) = unbox result
return resultConverter.Convert(actionContext.ControllerContext, value) }
Async.StartAsTask(computation, cancellationToken = cancellationToken)
override this.InvokeActionAsync(actionContext, cancellationToken) =
if actionContext = null then
raise <| ArgumentNullException("actionContext")
let actionDescriptor = actionContext.ActionDescriptor
Contract.Assert(actionDescriptor <> null)
let returnType = actionDescriptor.ReturnType
// For now, throw if the result is an IHttpActionResult.
if typeof<IHttpActionResult>.IsAssignableFrom(returnType) then
raise <| InvalidOperationException("IHttpResult is not supported when returning an Async")
match returnType with
| Async resultType ->
let specialized = asTaskMethod.MakeGenericMethod(resultType)
downcast specialized.Invoke(null, [| actionContext; cancellationToken |])
| _ -> base.InvokeActionAsync(actionContext, cancellationToken)
|
namespace System
namespace System.Diagnostics
namespace System.Diagnostics.Contracts
namespace System.Net
namespace System.Net.Http
namespace System.Reflection
namespace System.Web
namespace System.Web.Http
namespace System.Web.Http.Controllers
Multiple items
type AsyncApiActionInvoker =
inherit ApiControllerActionInvoker
new : unit -> AsyncApiActionInvoker
static member internal GetResultConverter : actionContext:HttpActionContext -> IActionResultConverter
static member internal StartAsTask : actionContext:HttpActionContext * cancellationToken:'a -> 'b
Full name: Script.AsyncApiActionInvoker
--------------------
new : unit -> AsyncApiActionInvoker
Multiple items
type ApiControllerActionInvoker =
new : unit -> ApiControllerActionInvoker
member InvokeActionAsync : actionContext:HttpActionContext * cancellationToken:CancellationToken -> Task<HttpResponseMessage>
Full name: System.Web.Http.Controllers.ApiControllerActionInvoker
--------------------
ApiControllerActionInvoker() : unit
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken
Full name: Microsoft.FSharp.Control.Async
--------------------
type Async<'T>
Full name: Microsoft.FSharp.Control.Async<_>
type Type =
inherit MemberInfo
member Assembly : Assembly
member AssemblyQualifiedName : string
member Attributes : TypeAttributes
member BaseType : Type
member ContainsGenericParameters : bool
member DeclaringMethod : MethodBase
member DeclaringType : Type
member Equals : o:obj -> bool + 1 overload
member FindInterfaces : filter:TypeFilter * filterCriteria:obj -> Type[]
member FindMembers : memberType:MemberTypes * bindingAttr:BindingFlags * filter:MemberFilter * filterCriteria:obj -> MemberInfo[]
...
Full name: System.Type
val typedefof<'T> : Type
Full name: Microsoft.FSharp.Core.Operators.typedefof
union case Option.Some: Value: 'T -> Option<'T>
union case Option.None: Option<'T>
val typeof<'T> : Type
Full name: Microsoft.FSharp.Core.Operators.typeof
type BindingFlags =
| Default = 0
| IgnoreCase = 1
| DeclaredOnly = 2
| Instance = 4
| Static = 8
| Public = 16
| NonPublic = 32
| FlattenHierarchy = 64
| InvokeMethod = 256
| CreateInstance = 512
...
Full name: System.Reflection.BindingFlags
field BindingFlags.NonPublic = 32
field BindingFlags.Static = 8
Multiple items
type VoidResultConverter =
new : unit -> VoidResultConverter
member Convert : controllerContext:HttpControllerContext * actionResult:obj -> HttpResponseMessage
Full name: System.Web.Http.Controllers.VoidResultConverter
--------------------
VoidResultConverter() : unit
static member internal AsyncApiActionInvoker.GetResultConverter : actionContext:HttpActionContext -> IActionResultConverter
Full name: Script.AsyncApiActionInvoker.GetResultConverter
Multiple items
type HttpActionContext =
new : unit -> HttpActionContext + 1 overload
member ActionArguments : Dictionary<string, obj>
member ActionDescriptor : HttpActionDescriptor with get, set
member ControllerContext : HttpControllerContext with get, set
member ModelState : ModelStateDictionary
member Request : HttpRequestMessage
member RequestContext : HttpRequestContext
member Response : HttpResponseMessage with get, set
Full name: System.Web.Http.Controllers.HttpActionContext
--------------------
HttpActionContext() : unit
HttpActionContext(controllerContext: HttpControllerContext, actionDescriptor: HttpActionDescriptor) : unit
type IActionResultConverter =
member Convert : controllerContext:HttpControllerContext * actionResult:obj -> HttpResponseMessage
Full name: System.Web.Http.Controllers.IActionResultConverter
val raise : exn:Exception -> 'T
Full name: Microsoft.FSharp.Core.Operators.raise
Multiple items
type InvalidOperationException =
inherit SystemException
new : unit -> InvalidOperationException + 2 overloads
Full name: System.InvalidOperationException
--------------------
InvalidOperationException() : unit
InvalidOperationException(message: string) : unit
InvalidOperationException(message: string, innerException: exn) : unit
type unit = Unit
Full name: Microsoft.FSharp.Core.unit
Multiple items
type ValueResultConverter<'T> =
new : unit -> ValueResultConverter<'T>
member Convert : controllerContext:HttpControllerContext * actionResult:obj -> HttpResponseMessage
Full name: System.Web.Http.Controllers.ValueResultConverter<_>
--------------------
ValueResultConverter() : unit
static member internal AsyncApiActionInvoker.StartAsTask : actionContext:HttpActionContext * cancellationToken:'a -> 'b
Full name: Script.AsyncApiActionInvoker.StartAsTask
static member internal AsyncApiActionInvoker.GetResultConverter : actionContext:HttpActionContext -> IActionResultConverter
val async : AsyncBuilder
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
static member Async.AwaitTask : task:Threading.Tasks.Task<'T> -> Async<'T>
val unbox : value:obj -> 'T
Full name: Microsoft.FSharp.Core.Operators.unbox
type Convert =
static val DBNull : obj
static member ChangeType : value:obj * typeCode:TypeCode -> obj + 3 overloads
static member FromBase64CharArray : inArray:char[] * offset:int * length:int -> byte[]
static member FromBase64String : s:string -> byte[]
static member GetTypeCode : value:obj -> TypeCode
static member IsDBNull : value:obj -> bool
static member ToBase64CharArray : inArray:byte[] * offsetIn:int * length:int * outArray:char[] * offsetOut:int -> int + 1 overload
static member ToBase64String : inArray:byte[] -> string + 3 overloads
static member ToBoolean : value:obj -> bool + 17 overloads
static member ToByte : value:obj -> byte + 18 overloads
...
Full name: System.Convert
static member Async.StartAsTask : computation:Async<'T> * ?taskCreationOptions:Threading.Tasks.TaskCreationOptions * ?cancellationToken:Threading.CancellationToken -> Threading.Tasks.Task<'T>
Multiple items
type ArgumentNullException =
inherit ArgumentException
new : unit -> ArgumentNullException + 3 overloads
Full name: System.ArgumentNullException
--------------------
ArgumentNullException() : unit
ArgumentNullException(paramName: string) : unit
ArgumentNullException(message: string, innerException: exn) : unit
ArgumentNullException(paramName: string, message: string) : unit
type Contract =
static member Assert : condition:bool -> unit + 1 overload
static member Assume : condition:bool -> unit + 1 overload
static member EndContractBlock : unit -> unit
static member Ensures : condition:bool -> unit + 1 overload
static member EnsuresOnThrow<'TException> : condition:bool -> unit + 1 overload
static member Exists<'T> : collection:IEnumerable<'T> * predicate:Predicate<'T> -> bool + 1 overload
static member ForAll<'T> : collection:IEnumerable<'T> * predicate:Predicate<'T> -> bool + 1 overload
static member Invariant : condition:bool -> unit + 1 overload
static member OldValue<'T> : value:'T -> 'T
static member Requires : condition:bool -> unit + 3 overloads
...
Full name: System.Diagnostics.Contracts.Contract
Contract.Assert(condition: bool) : unit
Contract.Assert(condition: bool, userMessage: string) : unit
type IHttpActionResult =
member ExecuteAsync : cancellationToken:CancellationToken -> Task<HttpResponseMessage>
Full name: System.Web.Http.IHttpActionResult
More information