-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathHttpContextExtensions.fs
More file actions
523 lines (469 loc) · 26.8 KB
/
HttpContextExtensions.fs
File metadata and controls
523 lines (469 loc) · 26.8 KB
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
namespace Giraffe
open System
open System.IO
open System.Text
open System.Globalization
open System.Runtime.CompilerServices
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Http.Extensions
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.Primitives
open Microsoft.Extensions.Logging
open Microsoft.Net.Http.Headers
open Giraffe.ViewEngine
type MissingDependencyException(dependencyName: string) =
inherit
Exception(
sprintf
"Could not retrieve object of type '%s' from ASP.NET Core's dependency container. Please register all Giraffe dependencies by adding `services.AddGiraffe()` to your startup code. For more information visit https://github.com/giraffe-fsharp/Giraffe."
dependencyName
)
[<Extension>]
type HttpContextExtensions() =
/// <summary>
/// Returns the entire request URL in a fully escaped form, which is suitable for use in HTTP headers and other operations.
/// </summary>
/// <returns>Returns a <see cref="System.String"/> URL.</returns>
[<Extension>]
static member GetRequestUrl(ctx: HttpContext) = ctx.Request.GetEncodedUrl()
/// <summary>
/// Gets an instance of `'T` from the request's service container.
/// </summary>
/// <returns>Returns an instance of `'T`.</returns>
[<Extension>]
static member GetService<'T>(ctx: HttpContext) =
let t = typeof<'T>
match ctx.RequestServices.GetService t with
| null -> raise (MissingDependencyException t.Name)
| service -> service :?> 'T
/// <summary>
/// Gets an instance of <see cref="Microsoft.Extensions.Logging.ILogger{T}" /> from the request's service container.
///
/// The type `'T` should represent the class or module from where the logger gets instantiated.
/// </summary>
/// <returns> Returns an instance of <see cref="Microsoft.Extensions.Logging.ILogger{T}" />.</returns>
[<Extension>]
static member GetLogger<'T>(ctx: HttpContext) = ctx.GetService<ILogger<'T>>()
/// <summary>
/// Gets an instance of <see cref="Microsoft.Extensions.Logging.ILogger"/> from the request's service container.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="categoryName">The category name for messages produced by this logger.</param>
/// <returns>Returns an instance of <see cref="Microsoft.Extensions.Logging.ILogger"/>.</returns>
[<Extension>]
static member GetLogger(ctx: HttpContext, categoryName: string) =
let loggerFactory = ctx.GetService<ILoggerFactory>()
loggerFactory.CreateLogger categoryName
[<Obsolete("Please use `GetWebHostEnvironment` as a replacement for `GetHostingEnvironment`. In the next major version this function will be removed.")>]
/// <summary>
/// Gets an instance of <see cref="Microsoft.Extensions.Hosting.IHostingEnvironment"/> from the request's service container.
/// </summary>
/// <returns>Returns an instance of <see cref="Microsoft.Extensions.Hosting.IHostingEnvironment"/>.</returns>
[<Extension>]
static member GetHostingEnvironment(ctx: HttpContext) = ctx.GetService<IHostingEnvironment>()
/// <summary>
/// Gets an instance of <see cref="Microsoft.AspNetCore.Hosting.IWebHostEnvironment"/> from the request's service container.
/// </summary>
/// <returns>Returns an instance of <see cref="Microsoft.AspNetCore.Hosting.IWebHostEnvironment"/>.</returns>
[<Extension>]
static member GetWebHostEnvironment(ctx: HttpContext) = ctx.GetService<IWebHostEnvironment>()
/// <summary>
/// Gets an instance of <see cref="Giraffe.Serialization.Json.ISerializer"/> from the request's service container.
/// </summary>
/// <returns>Returns an instance of <see cref="Giraffe.Serialization.Json.ISerializer"/>.</returns>
[<Extension>]
static member GetJsonSerializer(ctx: HttpContext) : Json.ISerializer = ctx.GetService<Json.ISerializer>()
/// <summary>
/// Gets an instance of <see cref="Giraffe.Serialization.Xml.Xml.ISerializer"/> from the request's service container.
/// </summary>
/// <returns>Returns an instance of <see cref="Giraffe.Serialization.Xml.Xml.ISerializer"/>.</returns>
[<Extension>]
static member GetXmlSerializer(ctx: HttpContext) : Xml.ISerializer = ctx.GetService<Xml.ISerializer>()
/// <summary>
/// Sets the HTTP status code of the response.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="httpStatusCode">The status code to be set in the response. For convenience you can use the static <see cref="Microsoft.AspNetCore.Http.StatusCodes"/> class for passing in named status codes instead of using pure int values.</param>
[<Extension>]
static member SetStatusCode(ctx: HttpContext, httpStatusCode: int) =
ctx.Response.StatusCode <- httpStatusCode
/// <summary>
/// Adds or sets a HTTP header in the response.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The HTTP header name. For convenience you can use the static <see cref="Microsoft.Net.Http.Headers.HeaderNames"/> class for passing in strongly typed header names instead of using pure `string` values.</param>
/// <param name="value">The value to be set. Non string values will be converted to a string using the object's ToString() method.</param>
[<Extension>]
static member SetHttpHeader(ctx: HttpContext, key: string, value: obj) =
ctx.Response.Headers.[key] <- StringValues(value.ToString())
/// <summary>
/// Sets the Content-Type HTTP header in the response.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="contentType">The mime type of the response (e.g.: application/json or text/html).</param>
[<Extension>]
static member SetContentType(ctx: HttpContext, contentType: string) =
ctx.SetHttpHeader(HeaderNames.ContentType, contentType)
/// <summary>
/// Tries to get the <see cref="System.String"/> value of a HTTP header from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the HTTP header.</param>
/// <returns> Returns Some string if the HTTP header was present in the request, otherwise returns None.</returns>
[<Extension>]
static member TryGetRequestHeader(ctx: HttpContext, key: string) =
match ctx.Request.Headers.TryGetValue key with
| true, value -> Some(value.ToString())
| _ -> None
/// <summary>
/// Retrieves the <see cref="System.String"/> value of a HTTP header from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the HTTP header.</param>
/// <returns>Returns Ok string if the HTTP header was present in the request, otherwise returns Error string.</returns>
[<Extension>]
static member GetRequestHeader(ctx: HttpContext, key: string) =
match ctx.Request.Headers.TryGetValue key with
| true, value -> Ok(value.ToString())
| _ -> Error(sprintf "HTTP request header '%s' is missing." key)
/// <summary>
/// Tries to get the <see cref="System.String"/> value of a query string parameter from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the query string parameter.</param>
/// <returns>Returns Some string if the parameter was present in the request's query string, otherwise returns None.</returns>
[<Extension>]
static member TryGetQueryStringValue(ctx: HttpContext, key: string) =
match ctx.Request.Query.TryGetValue key with
| true, value -> Some(value.ToString())
| _ -> None
/// <summary>
/// Retrieves the <see cref="System.String"/> value of a query string parameter from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the query string parameter.</param>
/// <returns>Returns Ok string if the parameter was present in the request's query string, otherwise returns Error string.</returns>
[<Extension>]
static member GetQueryStringValue(ctx: HttpContext, key: string) =
match ctx.Request.Query.TryGetValue key with
| true, value -> Ok(value.ToString())
| _ -> Error(sprintf "Query string value '%s' is missing." key)
/// <summary>
/// Retrieves the <see cref="System.String"/> value of a cookie from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the cookie.</param>
/// <returns>Returns Some string if the cookie was set, otherwise returns None.</returns>
[<Extension>]
static member GetCookieValue(ctx: HttpContext, key: string) =
match ctx.Request.Cookies.TryGetValue key with
| true, cookie -> Some cookie
| false, _ -> None
/// <summary>
/// Retrieves the <see cref="System.String"/> value of a form parameter from the request.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="key">The name of the form parameter.</param>
/// <returns>Returns Some string if the form parameter was set, otherwise returns None.</returns>
[<Extension>]
static member GetFormValue(ctx: HttpContext, key: string) =
match ctx.Request.HasFormContentType with
| false -> None
| true ->
match ctx.Request.Form.TryGetValue key with
| true, value -> Some(value.ToString())
| false, _ -> None
/// <summary>
/// Reads the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously and returns it as a <see cref="System.String"/> value.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <returns>Returns the contents of the request body as a <see cref="System.Threading.Tasks.Task{System.String}"/>.</returns>
[<Extension>]
static member ReadBodyFromRequestAsync(ctx: HttpContext) =
task {
use reader = new StreamReader(ctx.Request.Body, Encoding.UTF8, leaveOpen = true)
return! reader.ReadToEndAsync()
}
/// <summary>
/// Reads the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously and returns it as a <see cref="System.String"/> value. This function let's you decide if you want to leave the ctx.Request.Body element open or not.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="leaveOpen">`true` to leave the stream open after the StreamReader object is disposed; otherwise, `false`.</param>
/// <returns>Returns the contents of the request body as a <see cref="System.Threading.Tasks.Task{System.String}"/>.</returns>
[<Extension>]
static member ReadBodyFromRequestAsync(ctx: HttpContext, leaveOpen: bool) =
task {
use reader =
new StreamReader(ctx.Request.Body, Encoding.UTF8, leaveOpen = leaveOpen)
return! reader.ReadToEndAsync()
}
/// <summary>
/// Reads the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously and returns it as a <see cref="System.String"/> value.
/// This method buffers the response and makes subsequent reads possible.
/// </summary>
/// <returns>Returns the contents of the request body as a <see cref="System.Threading.Tasks.Task{System.String}"/>.</returns>
[<Extension>]
static member ReadBodyBufferedFromRequestAsync(ctx: HttpContext) =
task {
ctx.Request.EnableBuffering()
use reader =
new StreamReader(
ctx.Request.Body,
encoding = Encoding.UTF8,
detectEncodingFromByteOrderMarks = false,
leaveOpen = true
)
let! body = reader.ReadToEndAsync()
ctx.Request.Body.Position <- 0L
return body
}
/// <summary>
/// Uses the <see cref="Json.ISerializer"/> to deserialize the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously into an object of type 'T.
/// </summary>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns a <see cref="System.Threading.Tasks.Task{T}"/></returns>
[<Extension>]
static member BindJsonAsync<'T>(ctx: HttpContext) =
task {
let serializer = ctx.GetJsonSerializer()
return! serializer.DeserializeAsync<'T> ctx.Request.Body
}
/// <summary>
/// Uses the <see cref="Xml.ISerializer"/> to deserialize the entire body of the <see cref="Microsoft.AspNetCore.Http.HttpRequest"/> asynchronously into an object of type 'T.
/// </summary>
/// <typeparam name="'T"></typeparam>
/// <returns>Retruns a <see cref="System.Threading.Tasks.Task{T}"/></returns>
[<Extension>]
static member BindXmlAsync<'T>(ctx: HttpContext) =
task {
let serializer = ctx.GetXmlSerializer()
let! body = ctx.ReadBodyFromRequestAsync()
return serializer.Deserialize<'T> body
}
/// <summary>
/// Parses all input elements from an HTML form into an object of type 'T.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="cultureInfo">An optional <see cref="System.Globalization.CultureInfo"/> element to be used when parsing culture specific data such as float, DateTime or decimal values.</param>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns a <see cref="System.Threading.Tasks.Task{T}"/></returns>
[<Extension>]
static member BindFormAsync<'T>(ctx: HttpContext, ?cultureInfo: CultureInfo) =
task {
let! form = ctx.Request.ReadFormAsync()
return
form
|> Seq.map (fun i -> i.Key, i.Value)
|> dict
|> ModelParser.parse<'T> cultureInfo
}
/// <summary>
/// Tries to parse all input elements from an HTML form into an object of type 'T.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="cultureInfo">An optional <see cref="System.Globalization.CultureInfo"/> element to be used when parsing culture specific data such as float, DateTime or decimal values.</param>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns an object 'T if model binding succeeded, otherwise a <see cref="System.String"/> message containing the specific model parsing error.</returns>
[<Extension>]
static member TryBindFormAsync<'T>(ctx: HttpContext, ?cultureInfo: CultureInfo) =
task {
let! form = ctx.Request.ReadFormAsync()
return
form
|> Seq.map (fun i -> i.Key, i.Value)
|> dict
|> ModelParser.tryParse<'T> cultureInfo
}
/// <summary>
/// Parses all parameters of a request's query string into an object of type 'T.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="cultureInfo">An optional <see cref="System.Globalization.CultureInfo"/> element to be used when parsing culture specific data such as float, DateTime or decimal values.</param>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns an instance of type 'T</returns>
[<Extension>]
static member BindQueryString<'T>(ctx: HttpContext, ?cultureInfo: CultureInfo) =
ctx.Request.Query
|> Seq.map (fun i -> i.Key, i.Value)
|> dict
|> ModelParser.parse<'T> cultureInfo
/// <summary>
/// Tries to parse all parameters of a request's query string into an object of type 'T.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="cultureInfo">An optional <see cref="System.Globalization.CultureInfo"/> element to be used when parsing culture specific data such as float, DateTime or decimal values.</param>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns an object 'T if model binding succeeded, otherwise a <see cref="System.String"/> message containing the specific model parsing error.</returns>
[<Extension>]
static member TryBindQueryString<'T>(ctx: HttpContext, ?cultureInfo: CultureInfo) =
ctx.Request.Query
|> Seq.map (fun i -> i.Key, i.Value)
|> dict
|> ModelParser.tryParse<'T> cultureInfo
/// <summary>
/// Parses the request body into an object of type 'T based on the request's Content-Type header.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="cultureInfo">An optional <see cref="System.Globalization.CultureInfo"/> element to be used when parsing culture specific data such as float, DateTime or decimal values.</param>
/// <typeparam name="'T"></typeparam>
/// <returns>Returns a <see cref="System.Threading.Tasks.Task{T}"/></returns>
[<Extension>]
static member BindModelAsync<'T>(ctx: HttpContext, ?cultureInfo: CultureInfo) =
task {
let method = ctx.Request.Method
if
method.Equals "POST"
|| method.Equals "PUT"
|| method.Equals "PATCH"
|| method.Equals "DELETE"
then
let original = StringSegment(ctx.Request.ContentType)
let parsed = ref (MediaTypeHeaderValue(StringSegment("*/*")))
return!
match MediaTypeHeaderValue.TryParse(original, parsed) with
| false -> failwithf "Could not parse Content-Type HTTP header value '%s'" original.Value
| true ->
match parsed.Value.MediaType.Value with
| "application/json" -> ctx.BindJsonAsync<'T>()
| "application/xml" -> ctx.BindXmlAsync<'T>()
| "application/x-www-form-urlencoded" -> ctx.BindFormAsync<'T>(?cultureInfo = cultureInfo)
| _ -> failwithf "Cannot bind model from Content-Type '%s'" original.Value
else
return ctx.BindQueryString<'T>(?cultureInfo = cultureInfo)
}
/// <summary>
/// Writes a byte array to the body of the HTTP response and sets the HTTP Content-Length header accordingly.<br />
/// <br />
/// There are exceptions to be taken care of according to the RFC.<br />
/// 1. Don't send Content-Length headers on 1xx and 204 responses and on 2xx responses to CONNECT requests (https://httpwg.org/specs/rfc7230.html#rfc.section.3.3.2)<br />
/// 2. Don't send non-zero Content-Length headers for 205 responses (https://httpwg.org/specs/rfc7231.html#rfc.section.6.3.6)<br />
/// <br />
/// Since .NET 7 these rules are enforced by Kestrel (https://github.com/dotnet/aspnetcore/pull/43103)
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="bytes">The byte array to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteBytesAsync(ctx: HttpContext, bytes: byte[]) =
task {
let canIncludeContentLengthHeader =
match ctx.Response.StatusCode, ctx.Request.Method with
| statusCode, _ when statusCode |> is1xxStatusCode || statusCode = 204 -> false
| statusCode, method when method = "CONNECT" && statusCode |> is2xxStatusCode -> false
| _ -> true
let is205StatusCode = ctx.Response.StatusCode = 205
if canIncludeContentLengthHeader then
let contentLength = if is205StatusCode then 0 else bytes.Length
ctx.SetHttpHeader(HeaderNames.ContentLength, contentLength)
if ctx.Request.Method <> HttpMethods.Head then
do! ctx.Response.Body.WriteAsync(bytes, 0, bytes.Length)
return Some ctx
}
/// <summary>
/// Writes an UTF-8 encoded string to the body of the HTTP response and sets the HTTP Content-Length header accordingly.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="str">The string value to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteStringAsync(ctx: HttpContext, str: string) =
ctx.WriteBytesAsync(Encoding.UTF8.GetBytes str)
/// <summary>
/// Writes an UTF-8 encoded string to the body of the HTTP response and sets the HTTP `Content-Length` header accordingly, as well as the `Content-Type` header to `text/plain`.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="str">The string value to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteTextAsync(ctx: HttpContext, str: string) =
ctx.SetContentType "text/plain; charset=utf-8"
ctx.WriteStringAsync str
/// <summary>
/// Serializes an object to JSON and writes the output to the body of the HTTP response.
/// It also sets the HTTP Content-Type header to application/json and sets the Content-Length header accordingly.
/// The JSON serializer can be configured in the ASP.NET Core startup code by registering a custom class of type <see cref="Json.ISerializer"/>
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="dataObj">The object to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteJsonAsync<'T>(ctx: HttpContext, dataObj: 'T) =
ctx.SetContentType "application/json; charset=utf-8"
let serializer = ctx.GetJsonSerializer()
serializer.SerializeToBytes dataObj |> ctx.WriteBytesAsync
/// <summary>
/// Serializes an object to JSON and writes the output to the body of the HTTP response using chunked transfer encoding.
/// It also sets the HTTP Content-Type header to application/json and sets the Transfer-Encoding header to chunked.
/// The JSON serializer can be configured in the ASP.NET Core startup code by registering a custom class of type <see cref="Json.ISerializer"/>.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="dataObj">The object to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteJsonChunkedAsync<'T>(ctx: HttpContext, dataObj: 'T) =
task {
// Don't set the Transfer-Encoding to chunked manually. If we do, we'll have to do the chunking manually
// ourselves rather than rely on asp.net to do it for us.
// Example : https://github.com/aspnet/AspNetCore/blame/728110ec9ee1b98b2d9c9ff247ba2955d6c05846/src/Servers/Kestrel/test/InMemory.FunctionalTests/ChunkedResponseTests.cs#L494
ctx.SetContentType "application/json; charset=utf-8"
if ctx.Request.Method <> HttpMethods.Head then
let serializer = ctx.GetJsonSerializer()
do! serializer.SerializeToStreamAsync dataObj ctx.Response.Body
return Some ctx
}
/// <summary>
/// Serializes an object to XML and writes the output to the body of the HTTP response.
/// It also sets the HTTP Content-Type header to application/xml and sets the Content-Length header accordingly.
/// The JSON serializer can be configured in the ASP.NET Core startup code by registering a custom class of type <see cref="Xml.ISerializer"/>.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="dataObj">The object to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteXmlAsync(ctx: HttpContext, dataObj: obj) =
ctx.SetContentType "application/xml; charset=utf-8"
let serializer = ctx.GetXmlSerializer()
serializer.Serialize dataObj |> ctx.WriteBytesAsync
/// <summary>
/// Reads a HTML file from disk and writes its contents to the body of the HTTP response.
/// It also sets the HTTP header Content-Type to text/html and sets the Content-Length header accordingly.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="filePath">A relative or absolute file path to the HTML file.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteHtmlFileAsync(ctx: HttpContext, filePath: string) =
task {
let filePath =
match Path.IsPathRooted filePath with
| true -> filePath
| false ->
let env = ctx.GetWebHostEnvironment()
Path.Combine(env.ContentRootPath, filePath)
ctx.SetContentType "text/html; charset=utf-8"
let! html = readFileAsStringAsync filePath
return! ctx.WriteStringAsync html
}
/// <summary>
/// Writes a HTML string to the body of the HTTP response.
/// It also sets the HTTP header Content-Type to text/html and sets the Content-Length header accordingly.
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="html">The HTML string to be send back to the client.</param>
/// <returns>Task of Some HttpContext after writing to the body of the response.</returns>
[<Extension>]
static member WriteHtmlStringAsync(ctx: HttpContext, html: string) =
ctx.SetContentType "text/html; charset=utf-8"
ctx.WriteStringAsync html
/// <summary>
/// <para>Compiles a `Giraffe.GiraffeViewEngine.XmlNode` object to a HTML view and writes the output to the body of the HTTP response.</para>
/// <para>It also sets the HTTP header `Content-Type` to `text/html` and sets the `Content-Length` header accordingly.</para>
/// </summary>
/// <param name="ctx">The current http context object.</param>
/// <param name="htmlView">An `XmlNode` object to be send back to the client and which represents a valid HTML view.</param>
/// <returns>Task of `Some HttpContext` after writing to the body of the response.</returns>
[<Extension>]
static member WriteHtmlViewAsync(ctx: HttpContext, htmlView: XmlNode) =
let bytes = RenderView.AsBytes.htmlDocument htmlView
ctx.SetContentType "text/html; charset=utf-8"
ctx.WriteBytesAsync bytes