-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathHttpContext.cs
177 lines (133 loc) · 6.12 KB
/
HttpContext.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web.Caching;
using System.Web.SessionState;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.AspNetCore.SystemWebAdapters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace System.Web;
public class HttpContext : IServiceProvider
{
private static readonly HttpContextAccessor _accessor = new();
private readonly HttpContextCore _context;
private HttpRequest? _request;
private HttpResponse? _response;
private HttpServerUtility? _server;
private IDictionary? _items;
private TraceContext? _trace;
public static HttpContext? Current => _accessor.HttpContext;
internal HttpContext(HttpContextCore context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public HttpRequest Request => _request ??= new(_context.Request);
public HttpResponse Response => _response ??= new(_context.Response);
public IDictionary Items => _items ??= _context.Items.AsNonGeneric();
public HttpServerUtility Server => _server ??= new(_context);
public TraceContext Trace => _trace ??= new(_context);
public Exception? Error => _context.Features.Get<IRequestExceptionFeature>()?.Exceptions is [{ } error, ..] ? error : null;
[SuppressMessage("Performance", "CA1819:Properties should not return arrays", Justification = Constants.ApiFromAspNet)]
public Exception[] AllErrors => _context.Features.Get<IRequestExceptionFeature>()?.Exceptions.ToArray() ?? Array.Empty<Exception>();
public void ClearError() => _context.Features.Get<IRequestExceptionFeature>()?.Clear();
public void AddError(Exception ex) => _context.Features.Get<IRequestExceptionFeature>()?.Add(ex);
public RequestNotification CurrentNotification => _context.Features.GetRequired<IHttpApplicationFeature>().CurrentNotification;
public bool IsPostNotification => _context.Features.GetRequired<IHttpApplicationFeature>().IsPostNotification;
public HttpApplication ApplicationInstance => _context.Features.GetRequired<IHttpApplicationFeature>().Application;
public HttpApplicationState Application => ApplicationInstance.Application;
public Cache Cache => _context.RequestServices.GetRequiredService<Cache>();
/// <summary>
/// Gets whether the current request is running in the development environment.
/// </summary>
public bool IsDebuggingEnabled => _context.RequestServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment();
public IPrincipal User
{
get => _context.Features.Get<IPrincipalUserFeature>()?.User ?? _context.User;
set
{
if (_context.Features.Get<IPrincipalUserFeature>() is { } feature)
{
feature.User = value;
}
else
{
var newFeature = new PrincipalUserFeature(_context) { User = value };
_context.Features.Set<IPrincipalUserFeature>(newFeature);
_context.Features.Set<IHttpAuthenticationFeature>(newFeature);
}
}
}
public HttpSessionState? Session => _context.Features.Get<HttpSessionState>();
public DateTime Timestamp => _context.Features.GetRequired<ITimestampFeature>().Timestamp.DateTime;
public void RewritePath(string path) => RewritePath(path, true);
public void RewritePath(string path, bool rebaseClientPath)
{
ArgumentNullException.ThrowIfNull(path);
// Extract query string
string? qs = null;
var iqs = path.IndexOf('?', StringComparison.Ordinal);
if (iqs >= 0)
{
qs = (iqs < path.Length - 1) ? path[iqs..] : string.Empty;
path = path[..iqs];
}
if (!path.StartsWith('/'))
{
path = "/" + path;
}
RewritePath(path.Trim(), string.Empty, qs, rebaseClientPath);
}
public void RewritePath(string filePath, string pathInfo, string? queryString)
=> RewritePath(filePath, pathInfo, queryString, false);
public void RewritePath(string filePath, string pathInfo, string? queryString, bool setClientFilePath)
=> _context.Features.GetRequired<IHttpRequestPathFeature>().Rewrite(filePath, pathInfo, queryString, setClientFilePath);
[SuppressMessage("Design", "CA1033:Interface methods should be callable by child types", Justification = Constants.ApiFromAspNet)]
object? IServiceProvider.GetService(Type service)
{
if (service == typeof(HttpRequest))
{
return Request;
}
else if (service == typeof(HttpResponse))
{
return Response;
}
else if (service == typeof(HttpSessionState))
{
return Session;
}
else if (service == typeof(HttpServerUtility))
{
return Server;
}
return null;
}
public ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target)
{
var token = new DisposeOnPipelineSubscriptionToken(target);
_context.Response.RegisterForDispose(token);
return token;
}
[return: NotNullIfNotNull(nameof(context))]
public static implicit operator HttpContext?(HttpContextCore? context) => context?.GetAdapter();
[return: NotNullIfNotNull(nameof(context))]
public static implicit operator HttpContextCore?(HttpContext? context) => context?._context;
private sealed class DisposeOnPipelineSubscriptionToken : ISubscriptionToken, IDisposable
{
private IDisposable? _other;
public DisposeOnPipelineSubscriptionToken(IDisposable other) => _other = other;
bool ISubscriptionToken.IsActive => _other is not null;
void ISubscriptionToken.Unsubscribe() => _other = null;
void IDisposable.Dispose()
{
_other?.Dispose();
_other = null;
}
}
}