-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathHttpContext.cs
196 lines (148 loc) · 6.89 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// 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.Hosting;
using System.Web.SessionState;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.AspNetCore.SystemWebAdapters;
using Microsoft.AspNetCore.SystemWebAdapters.Features;
using Microsoft.AspNetCore.SystemWebAdapters.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace System.Web;
public class HttpContext : IServiceProvider
{
private HttpRequest? _request;
private HttpResponse? _response;
private HttpServerUtility? _server;
private IDictionary? _items;
private TraceContext? _trace;
public static HttpContext? Current
{
get => HostingEnvironmentAccessor.HttpContextAccessor.HttpContext?.AsSystemWeb();
set => HostingEnvironmentAccessor.HttpContextAccessor.HttpContext = value?.AsAspNetCore();
}
internal HttpContext(HttpContextCore context)
{
Context = context ?? throw new ArgumentNullException(nameof(context));
}
internal HttpContextCore Context { get; }
public HttpRequest Request => _request ??= new(Context.Request);
public HttpResponse Response => _response ??= new(Context.Response);
public IDictionary Items
{
get
{
if (_items is null)
{
var items = Context.Items;
_items = items is IDictionary d ? d : new NonGenericDictionaryWrapper(items);
}
return _items;
}
}
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.GetRequiredFeature<IHttpApplicationFeature>().CurrentNotification;
public bool IsPostNotification => Context.Features.GetRequiredFeature<IHttpApplicationFeature>().IsPostNotification;
public HttpApplication ApplicationInstance => Context.Features.GetRequiredFeature<IHttpApplicationFeature>().Application;
public HttpApplicationState Application => ApplicationInstance.Application;
public Cache Cache => Context.RequestServices.GetRequiredService<Cache>();
public IHttpHandler? Handler
{
get => Context.Features.GetRequiredFeature<IHttpHandlerFeature>().Current;
set => Context.Features.GetRequiredFeature<IHttpHandlerFeature>().Current = value;
}
public IHttpHandler? CurrentHandler => Handler;
public IHttpHandler? PreviousHandler => Context.Features.GetRequiredFeature<IHttpHandlerFeature>().Previous;
public void RemapHandler(IHttpHandler handler) => Handler = handler;
/// <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<IRequestUserFeature>()?.User ?? Context.User;
set => Context.GetRequestUser().User = value;
}
public HttpSessionState? Session => Context.Features.Get<ISessionStateFeature>()?.Session;
public void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior)
=> Context.Features.GetRequiredFeature<ISessionStateFeature>().Behavior = sessionStateBehavior;
public DateTime Timestamp => Context.Features.GetRequiredFeature<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.GetRequiredFeature<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 Context.RequestServices?.GetService(service);
}
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?.AsSystemWeb();
[return: NotNullIfNotNull(nameof(context))]
public static implicit operator HttpContextCore?(HttpContext? context) => context?.AsAspNetCore();
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;
}
}
}