-
-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathHttpPortalController.cs
304 lines (276 loc) · 11 KB
/
HttpPortalController.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
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
//-----------------------------------------------------------------------
// <copyright file="HttpPortalController.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Exposes server-side DataPortal functionality</summary>
//-----------------------------------------------------------------------
using System.Diagnostics.CodeAnalysis;
using Csla.Serialization;
using Csla.Server.Hosts.DataPortalChannel;
#if NETSTANDARD2_0 || NET8_0_OR_GREATER
using Microsoft.AspNetCore.Mvc;
#else
using System.Net.Http;
using System.Web.Http;
#endif
namespace Csla.Server.Hosts
{
/// <summary>
/// Exposes server-side DataPortal functionality
/// through HTTP request/response.
/// </summary>
#if NETSTANDARD2_0 || NET8_0_OR_GREATER
public class HttpPortalController : Controller
{
private ApplicationContext _applicationContext;
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="applicationContext">ApplicationContext instance.</param>
public HttpPortalController(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
/// <summary>
/// Gets or sets a value indicating whether to use
/// text/string serialization instead of the default
/// binary serialization.
/// </summary>
public bool UseTextSerialization { get; set; } = false;
/// <summary>
/// Entry point for all data portal operations.
/// </summary>
/// <param name="operation">Name of the data portal operation to perform.</param>
/// <returns>Results from the server-side data portal.</returns>
[HttpPost]
public virtual async Task PostAsync([FromQuery] string operation)
{
if (operation.Contains("/"))
{
var temp = operation.Split('/');
await PostAsync(temp[0], temp[1]);
}
else
{
if (UseTextSerialization)
await InvokeTextPortal(operation, Request.Body, Response.Body).ConfigureAwait(false);
else
await InvokePortal(operation, Request.Body, Response.Body).ConfigureAwait(false);
}
}
private static HttpClient? _client;
/// <summary>
/// Gets a dictionary containing the URLs for each
/// data portal route, where each key is the
/// routing tag identifying the route URL.
/// </summary>
protected static Dictionary<string, string> RoutingTagUrls { get; set; } = [];
/// <summary>
/// Gets or sets the HttpClient timeout
/// in milliseconds (0 uses default HttpClient timeout).
/// </summary>
protected int HttpClientTimeout { get; set; }
/// <summary>
/// Gets an HttpClient object for use in
/// communication with the server.
/// </summary>
[MemberNotNull(nameof(_client))]
protected virtual HttpClient GetHttpClient()
{
if (_client == null)
{
_client = new HttpClient();
if (HttpClientTimeout > 0)
{
_client.Timeout = TimeSpan.FromMilliseconds(HttpClientTimeout);
}
}
return _client;
}
/// <summary>
/// Entry point for routing tag based data portal operations.
/// </summary>
/// <param name="operation">Name of the data portal operation to perform.</param>
/// <param name="routingTag">Routing tag from caller</param>
protected virtual async Task PostAsync(string operation, string routingTag)
{
if (RoutingTagUrls.TryGetValue(routingTag, out string? route) && route != "localhost")
{
var httpRequest = new HttpRequestMessage(HttpMethod.Post, $"{route}?operation={operation}");
using (var buffer = new MemoryStream())
{
await Request.Body.CopyToAsync(buffer);
httpRequest.Content = new ByteArrayContent(buffer.ToArray());
}
var response = await GetHttpClient().SendAsync(httpRequest);
await response.Content.CopyToAsync(Response.Body);
}
else
{
await PostAsync(operation).ConfigureAwait(false);
}
}
#else // NET462 and MVC5
public class HttpPortalController : ApiController
{
private ApplicationContext _applicationContext;
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="applicationContext">ApplicationContext instance.</param>
public HttpPortalController(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
/// <summary>
/// Entry point for all data portal operations.
/// </summary>
/// <param name="operation">Name of the data portal operation to perform.</param>
/// <returns>Results from the server-side data portal.</returns>
public virtual async Task<HttpResponseMessage> PostAsync(string operation)
{
var requestData = await Request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var responseData = await InvokePortal(operation, requestData).ConfigureAwait(false);
var response = Request.CreateResponse();
response.Content = new ByteArrayContent(responseData);
return response;
}
#endif
private HttpPortal? _portal;
/// <summary>
/// Gets or sets the HttpPortal implementation
/// used to coordinate the data portal
/// operations.
/// </summary>
public HttpPortal Portal
{
get => _portal ??= _applicationContext.CreateInstanceDI<HttpPortal>();
set => _portal = value;
}
#if NETSTANDARD2_0 || NET8_0_OR_GREATER
/// <summary>
/// Override to add elements to the HttpReponse
/// headers.
/// </summary>
/// <param name="response">HttpResponse instance</param>
/// <remarks>
/// For example, you may allow compressed payloads:
/// response.Headers.Add("Accept-Encoding", "gzip,deflate");
/// </remarks>
protected virtual void SetHttpResponseHeaders(Microsoft.AspNetCore.Http.HttpResponse response)
{ }
private async Task InvokePortal(string operation, Stream requestStream, Stream responseStream)
{
var serializer = _applicationContext.GetRequiredService<ISerializationFormatter>();
var result = _applicationContext.CreateInstanceDI<DataPortalResponse>();
DataPortalErrorInfo? errorData = null;
if (UseTextSerialization)
Response.Headers.ContentType = "text/plain";
else
Response.Headers.ContentType = "application/octet-stream";
SetHttpResponseHeaders(Response);
try
{
var request = await DeserializeRequestBody(requestStream, serializer);
result = await CallPortal(operation, request);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
errorData = _applicationContext.CreateInstance<DataPortalErrorInfo>(_applicationContext, ex);
}
#pragma warning restore CA1031 // Do not catch general exception types
var portalResult = _applicationContext.CreateInstanceDI<DataPortalResponse>();
portalResult.ErrorData = errorData;
portalResult.ObjectData = result.ObjectData;
await SerializeToResponse(portalResult, responseStream, serializer);
}
private async Task InvokeTextPortal(string operation, Stream requestStream, Stream responseStream)
{
Response.Headers.ContentType = "text/plain";
string requestString;
using (var reader = new StreamReader(requestStream))
requestString = await reader.ReadToEndAsync();
var requestArray = Convert.FromBase64String(requestString);
var requestBuffer = new MemoryStream(requestArray);
var serializer = _applicationContext.GetRequiredService<ISerializationFormatter>();
var result = _applicationContext.CreateInstanceDI<DataPortalResponse>();
DataPortalErrorInfo? errorData = null;
try
{
var request = serializer.Deserialize(requestBuffer);
result = await CallPortal(operation, request);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
errorData = _applicationContext.CreateInstance<DataPortalErrorInfo>(_applicationContext, ex);
}
#pragma warning restore CA1031 // Do not catch general exception types
var portalResult = _applicationContext.CreateInstanceDI<DataPortalResponse>();
portalResult.ErrorData = errorData;
portalResult.ObjectData = result.ObjectData;
var responseBuffer = new MemoryStream();
serializer.Serialize(responseBuffer, portalResult);
responseBuffer.Position = 0;
using var writer = new StreamWriter(responseStream)
{
AutoFlush = true
};
await writer.WriteAsync(Convert.ToBase64String(responseBuffer.ToArray()));
}
#else
private async Task<byte[]> InvokePortal(string operation, byte[] data)
{
var result = _applicationContext.CreateInstance<DataPortalResponse>();
DataPortalErrorInfo? errorData = null;
try
{
var buffer = new MemoryStream(data)
{
Position = 0
};
var request = _applicationContext.GetRequiredService<ISerializationFormatter>().Deserialize(buffer.ToArray());
result = await CallPortal(operation, request);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
{
errorData = _applicationContext.CreateInstance<DataPortalErrorInfo>(_applicationContext, ex);
}
#pragma warning restore CA1031 // Do not catch general exception types
var portalResult = _applicationContext.CreateInstance<DataPortalResponse>();
portalResult.ErrorData = errorData;
portalResult.ObjectData = result.ObjectData;
var bytes = _applicationContext.GetRequiredService<ISerializationFormatter>().Serialize(portalResult);
return bytes;
}
#endif
private async Task<DataPortalResponse> CallPortal(string operation, object request)
{
var portal = Portal;
DataPortalResponse result = operation switch
{
"create" => await portal.Create((CriteriaRequest)request).ConfigureAwait(false),
"fetch" => await portal.Fetch((CriteriaRequest)request).ConfigureAwait(false),
"update" => await portal.Update((UpdateRequest)request).ConfigureAwait(false),
"delete" => await portal.Delete((CriteriaRequest)request).ConfigureAwait(false),
_ => throw new InvalidOperationException(operation),
};
return result;
}
private async Task<object> DeserializeRequestBody(Stream requestBody, ISerializationFormatter serializer) {
using var requestBodyBuffer = new MemoryStream();
await requestBody.CopyToAsync(requestBodyBuffer).ConfigureAwait(false);
requestBodyBuffer.Seek(0, SeekOrigin.Begin);
return serializer.Deserialize(requestBodyBuffer);
}
private async Task SerializeToResponse(DataPortalResponse portalResult, Stream responseStream, ISerializationFormatter serializer) {
using var responseBodyBuffer = new MemoryStream();
serializer.Serialize(responseBodyBuffer, portalResult);
responseBodyBuffer.Seek(0, SeekOrigin.Begin);
await responseBodyBuffer.CopyToAsync(responseStream).ConfigureAwait(false);
}
}
}