-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCommunicationMiddleware.cs
More file actions
54 lines (46 loc) · 1.83 KB
/
CommunicationMiddleware.cs
File metadata and controls
54 lines (46 loc) · 1.83 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
using System;
using System.Net;
using System.Threading.Tasks;
using ManagedCode.Communication.Extensions.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ManagedCode.Communication.Extensions;
public class CommunicationMiddleware
{
private readonly ILogger<CommunicationMiddleware> _logger;
private readonly RequestDelegate _next;
private readonly IOptions<CommunicationOptions> _options;
public CommunicationMiddleware(ILogger<CommunicationMiddleware> logger, RequestDelegate next,
IOptions<CommunicationOptions> options)
{
_logger = logger;
_next = next;
_options = options;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
_logger.LogError(ex, httpContext.Request.Method + "::" + httpContext.Request.Path);
if (httpContext.Response.HasStarted)
throw;
httpContext.Response.Headers.CacheControl = "no-cache,no-store";
httpContext.Response.Headers.Pragma = "no-cache";
httpContext.Response.Headers.Expires = "-1";
httpContext.Response.Headers.ETag = default;
httpContext.Response.ContentType = "application/json; charset=utf-8";
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
if (_options.Value.ShowErrorDetails)
await httpContext.Response.WriteAsJsonAsync(Result.Fail(HttpStatusCode.InternalServerError,
ex.Message));
else
await httpContext.Response.WriteAsJsonAsync(Result.Fail(HttpStatusCode.InternalServerError,
nameof(HttpStatusCode.InternalServerError)));
}
}
}