This repository has been archived by the owner on Dec 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 108
/
StatusCodePagesMiddleware.cs
55 lines (47 loc) · 1.98 KB
/
StatusCodePagesMiddleware.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
// 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.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Diagnostics
{
public class StatusCodePagesMiddleware
{
private readonly RequestDelegate _next;
private readonly StatusCodePagesOptions _options;
public StatusCodePagesMiddleware(RequestDelegate next, IOptions<StatusCodePagesOptions> options)
{
_next = next;
_options = options.Value;
if (_options.HandleAsync == null)
{
throw new ArgumentException("Missing options.HandleAsync implementation.");
}
}
public async Task Invoke(HttpContext context)
{
var statusCodeFeature = new StatusCodePagesFeature();
context.Features.Set<IStatusCodePagesFeature>(statusCodeFeature);
await _next(context);
if (!statusCodeFeature.Enabled)
{
// Check if the feature is still available because other middleware (such as a web API written in MVC) could
// have disabled the feature to prevent HTML status code responses from showing up to an API client.
return;
}
// Do nothing if a response body has already been provided.
if (context.Response.HasStarted
|| context.Response.StatusCode < 400
|| context.Response.StatusCode >= 600
|| context.Response.ContentLength.HasValue
|| !string.IsNullOrEmpty(context.Response.ContentType))
{
return;
}
var statusCodeContext = new StatusCodeContext(context, _options, _next);
await _options.HandleAsync(statusCodeContext);
}
}
}