| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Retrieves a request body value from the HTTP request. |
| | | 4 | | .DESCRIPTION |
| | | 5 | | This function accesses the current HTTP request context and retrieves the value |
| | | 6 | | of the request body. |
| | | 7 | | .PARAMETER Raw |
| | | 8 | | If specified, retrieves the raw request body without any parsing. |
| | | 9 | | .PARAMETER Type |
| | | 10 | | Specifies the type to which the request body should be deserialized. |
| | | 11 | | .EXAMPLE |
| | | 12 | | $value = Get-KrRequestBody |
| | | 13 | | Retrieves the value of the request body from the HTTP request. |
| | | 14 | | .EXAMPLE |
| | | 15 | | $value = Get-KrRequestBody -Raw |
| | | 16 | | Retrieves the raw request body from the HTTP request without any parsing. |
| | | 17 | | .OUTPUTS |
| | | 18 | | Returns the value of the request body, or $null if not found. |
| | | 19 | | .NOTES |
| | | 20 | | This function is designed to be used in the context of a Kestrun server response. |
| | | 21 | | #> |
| | | 22 | | function Get-KrRequestBody { |
| | | 23 | | [KestrunRuntimeApi('Route')] |
| | | 24 | | [CmdletBinding()] |
| | | 25 | | [OutputType([Hashtable])] |
| | | 26 | | param( |
| | | 27 | | [switch]$Raw, |
| | | 28 | | [Type]$Type |
| | | 29 | | ) |
| | | 30 | | |
| | 0 | 31 | | if ($null -ne $Context.Request) { |
| | 0 | 32 | | $body = $Context.Request.Body |
| | | 33 | | # Return the raw body if specified |
| | 0 | 34 | | if ($Raw) { |
| | | 35 | | # Get the raw request body value from the request |
| | 0 | 36 | | return $body |
| | | 37 | | } |
| | | 38 | | # Parse the request body based on the specified type or content type |
| | 0 | 39 | | if ($null -ne $Type) { |
| | 0 | 40 | | return [Kestrun.Utilities.Json.JsonSerializerHelper]::FromJson($body, $Type) |
| | | 41 | | } |
| | | 42 | | # Parse based on Content-Type |
| | 0 | 43 | | switch ($Context.Request.ContentType) { |
| | | 44 | | 'application/json' { |
| | 0 | 45 | | return $body | ConvertFrom-Json -AsHashtable |
| | | 46 | | } |
| | | 47 | | 'application/yaml' { |
| | 0 | 48 | | return [Kestrun.Utilities.YamlHelper]::ToHashtable( $body) |
| | | 49 | | } |
| | | 50 | | 'application/x-www-form-urlencoded' { |
| | 0 | 51 | | return $Context.Request.Form |
| | | 52 | | } |
| | | 53 | | 'application/xml' { |
| | 0 | 54 | | return [Kestrun.Utilities.XmlHelper]::ToHashtable( $body) |
| | | 55 | | } |
| | | 56 | | default { |
| | 0 | 57 | | return $body |
| | | 58 | | } |
| | | 59 | | } |
| | | 60 | | } |
| | | 61 | | } |