This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathBufferingHelper.cs
80 lines (68 loc) · 2.74 KB
/
BufferingHelper.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.AspNetCore.WebUtilities;
namespace Microsoft.AspNetCore.Http.Internal
{
public static class BufferingHelper
{
internal const int DefaultBufferThreshold = 1024 * 30;
private readonly static Func<string> _getTempDirectory = () => TempDirectory;
private static string _tempDirectory;
public static string TempDirectory
{
get
{
if (_tempDirectory == null)
{
// Look for folders in the following order.
var temp = Environment.GetEnvironmentVariable("ASPNETCORE_TEMP") ?? // ASPNETCORE_TEMP - User set temporary location.
Path.GetTempPath(); // Fall back.
if (!Directory.Exists(temp))
{
// TODO: ???
throw new DirectoryNotFoundException(temp);
}
_tempDirectory = temp;
}
return _tempDirectory;
}
}
public static HttpRequest EnableRewind(this HttpRequest request, int bufferThreshold = DefaultBufferThreshold, long? bufferLimit = null)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
var body = request.Body;
if (!body.CanSeek)
{
var fileStream = new FileBufferingReadStream(body, bufferThreshold, bufferLimit, _getTempDirectory);
request.Body = fileStream;
request.HttpContext.Response.RegisterForDispose(fileStream);
}
return request;
}
public static MultipartSection EnableRewind(this MultipartSection section, Action<IDisposable> registerForDispose,
int bufferThreshold = DefaultBufferThreshold, long? bufferLimit = null)
{
if (section == null)
{
throw new ArgumentNullException(nameof(section));
}
if (registerForDispose == null)
{
throw new ArgumentNullException(nameof(registerForDispose));
}
var body = section.Body;
if (!body.CanSeek)
{
var fileStream = new FileBufferingReadStream(body, bufferThreshold, bufferLimit, _getTempDirectory);
section.Body = fileStream;
registerForDispose(fileStream);
}
return section;
}
}
}