Skip to content

Commit 221a194

Browse files
author
Sergey Tregub
committed
Untabify files
1 parent b0325c5 commit 221a194

4 files changed

Lines changed: 133 additions & 133 deletions

File tree

ProjectTemplates/ReferenceProject/Constants.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ public static class Swagger
99
public static string Version => "v1";
1010
}
1111

12-
public static class Health
13-
{
14-
public static string EndPoint => "/health";
15-
}
12+
public static class Health
13+
{
14+
public static string EndPoint => "/health";
15+
}
1616
}
1717
}

ProjectTemplates/ReferenceProject/Middleware/ExceptionMiddleware.cs

Lines changed: 86 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -10,101 +10,101 @@
1010

1111
namespace ReferenceProject.Middleware
1212
{
13-
/// <summary>
14-
/// Middleware to handle exceptions.
15-
/// It separates exceptions based on their type and returns different status codes and answers based on it, instead of 500 Internal Server Error code in all cases.
16-
/// In addition, it writes them in the log.
17-
/// </summary>
18-
/// <remarks>
19-
/// There is another way to do this - an exception filter.
20-
/// However, a middleware is a preferred way to achieve this according to the official documentation.
21-
/// To learn more see https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#exception-filters
22-
///
23-
/// See also: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#unhandled-exceptions-handling
24-
/// </remarks>
25-
public class ExceptionMiddleware
26-
{
27-
RequestDelegate Next { get; }
28-
ILogger Logger { get; }
29-
IHostEnvironment Environment { get; }
13+
/// <summary>
14+
/// Middleware to handle exceptions.
15+
/// It separates exceptions based on their type and returns different status codes and answers based on it, instead of 500 Internal Server Error code in all cases.
16+
/// In addition, it writes them in the log.
17+
/// </summary>
18+
/// <remarks>
19+
/// There is another way to do this - an exception filter.
20+
/// However, a middleware is a preferred way to achieve this according to the official documentation.
21+
/// To learn more see https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#exception-filters
22+
///
23+
/// See also: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#unhandled-exceptions-handling
24+
/// </remarks>
25+
public class ExceptionMiddleware
26+
{
27+
RequestDelegate Next { get; }
28+
ILogger Logger { get; }
29+
IHostEnvironment Environment { get; }
3030

31-
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment environment)
32-
{
33-
Environment = environment ?? throw new ArgumentNullException(nameof(environment));
34-
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
35-
Next = next ?? throw new ArgumentNullException(nameof(next));
36-
}
31+
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment environment)
32+
{
33+
Environment = environment ?? throw new ArgumentNullException(nameof(environment));
34+
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
35+
Next = next ?? throw new ArgumentNullException(nameof(next));
36+
}
3737

38-
public async Task InvokeAsync(HttpContext context)
39-
{
40-
var body = context.Response.Body;
41-
try
42-
{
43-
await Next(context);
44-
}
45-
catch (Exception ex)
46-
{
47-
// If context.Response.HasStarted == true, then we can't write to the response stream anymore. So we have to restore the body.
48-
// If we don't do that we get an exception.
49-
context.Response.Body = body;
50-
await HandleExceptionAsync(context, ex);
51-
}
52-
}
38+
public async Task InvokeAsync(HttpContext context)
39+
{
40+
var body = context.Response.Body;
41+
try
42+
{
43+
await Next(context);
44+
}
45+
catch (Exception ex)
46+
{
47+
// If context.Response.HasStarted == true, then we can't write to the response stream anymore. So we have to restore the body.
48+
// If we don't do that we get an exception.
49+
context.Response.Body = body;
50+
await HandleExceptionAsync(context, ex);
51+
}
52+
}
5353

54-
async Task HandleExceptionAsync(HttpContext context, Exception ex)
55-
{
56-
int statusCode = 500;
54+
async Task HandleExceptionAsync(HttpContext context, Exception ex)
55+
{
56+
int statusCode = 500;
5757

58-
context.Response.ContentType = "application/json";
59-
context.Response.StatusCode = statusCode;
58+
context.Response.ContentType = "application/json";
59+
context.Response.StatusCode = statusCode;
6060

61-
// We can decide what the status code should return
62-
if (ex is KeyNotFoundException)
63-
{
64-
context.Response.StatusCode = StatusCodes.Status404NotFound;
65-
}
66-
else if (ex is DuplicateKeyException)
67-
{
68-
context.Response.StatusCode = StatusCodes.Status400BadRequest;
69-
}
61+
// We can decide what the status code should return
62+
if (ex is KeyNotFoundException)
63+
{
64+
context.Response.StatusCode = StatusCodes.Status404NotFound;
65+
}
66+
else if (ex is DuplicateKeyException)
67+
{
68+
context.Response.StatusCode = StatusCodes.Status400BadRequest;
69+
}
7070

71-
await context.Response.WriteAsync(
72-
JsonConvert.SerializeObject(
73-
new ErrorResponse(ex, Environment.IsDevelopment())));
71+
await context.Response.WriteAsync(
72+
JsonConvert.SerializeObject(
73+
new ErrorResponse(ex, Environment.IsDevelopment())));
7474

75-
if (context.Response.StatusCode == StatusCodes.Status500InternalServerError)
76-
{
77-
Logger.LogError(ex, "Unhandled exception occurred");
78-
}
79-
else
80-
{
81-
Logger.LogDebug(ex, "Unhandled exception occurred");
82-
}
83-
}
75+
if (context.Response.StatusCode == StatusCodes.Status500InternalServerError)
76+
{
77+
Logger.LogError(ex, "Unhandled exception occurred");
78+
}
79+
else
80+
{
81+
Logger.LogDebug(ex, "Unhandled exception occurred");
82+
}
83+
}
8484

85-
class ErrorResponse
86-
{
87-
public ErrorResponse(Exception ex, bool includeFullExceptionInfo)
88-
{
89-
Error = new ExceptionDescription(ex);
90-
if (includeFullExceptionInfo)
91-
{
92-
Error.Exception = ex;
93-
}
94-
}
85+
class ErrorResponse
86+
{
87+
public ErrorResponse(Exception ex, bool includeFullExceptionInfo)
88+
{
89+
Error = new ExceptionDescription(ex);
90+
if (includeFullExceptionInfo)
91+
{
92+
Error.Exception = ex;
93+
}
94+
}
9595

96-
public ExceptionDescription Error { get; set; }
97-
}
96+
public ExceptionDescription Error { get; set; }
97+
}
9898

99-
class ExceptionDescription
100-
{
101-
public ExceptionDescription(Exception ex)
102-
{
103-
Message = ex.Message;
104-
}
99+
class ExceptionDescription
100+
{
101+
public ExceptionDescription(Exception ex)
102+
{
103+
Message = ex.Message;
104+
}
105105

106-
public string Message { get; set; }
107-
public Exception Exception { get; set; }
108-
}
109-
}
106+
public string Message { get; set; }
107+
public Exception Exception { get; set; }
108+
}
109+
}
110110
}

ProjectTemplates/ReferenceProject/Program.cs

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -8,39 +8,39 @@
88

99
namespace ReferenceProject
1010
{
11-
public class Program
12-
{
13-
public static void Main(string[] args)
14-
{
15-
CreateHostBuilder(args).Build().Run();
16-
}
11+
public class Program
12+
{
13+
public static void Main(string[] args)
14+
{
15+
CreateHostBuilder(args).Build().Run();
16+
}
1717

18-
public static IHostBuilder CreateHostBuilder(string[] args) =>
19-
Host.CreateDefaultBuilder(args)
20-
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
21-
.ConfigureLogging((context, logging) =>
22-
{
23-
logging.ClearProviders();
18+
public static IHostBuilder CreateHostBuilder(string[] args) =>
19+
Host.CreateDefaultBuilder(args)
20+
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
21+
.ConfigureLogging((context, logging) =>
22+
{
23+
logging.ClearProviders();
2424

25-
/*
25+
/*
2626
* You can use a global logger as this, but I don't recommend this way
2727
* More information: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#logging
2828
Log.Logger = new LoggerConfiguration()
2929
.ReadFrom.Configuration(context.Configuration)
3030
.CreateLogger();
3131
*/
3232

33-
logging.AddSerilog(new LoggerConfiguration()
34-
.ReadFrom.Configuration(context.Configuration)
35-
.CreateLogger());
36-
})
37-
.ConfigureAppConfiguration(x =>
38-
{
39-
x.AddEnvironmentVariables();
40-
})
41-
.ConfigureWebHostDefaults(webBuilder =>
42-
{
43-
webBuilder.UseStartup<Startup>();
44-
});
45-
}
33+
logging.AddSerilog(new LoggerConfiguration()
34+
.ReadFrom.Configuration(context.Configuration)
35+
.CreateLogger());
36+
})
37+
.ConfigureAppConfiguration(x =>
38+
{
39+
x.AddEnvironmentVariables();
40+
})
41+
.ConfigureWebHostDefaults(webBuilder =>
42+
{
43+
webBuilder.UseStartup<Startup>();
44+
});
45+
}
4646
}

ProjectTemplates/ReferenceProject/Startup.cs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ public void ConfigureServices(IServiceCollection services)
7575
options.Filters.Add(new CacheControlFilter()); // Add "Cache-Control" header. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#cache-control
7676
})
7777
.AddApiExplorer()
78-
/*
79-
* TODO: Must be removed
80-
* This code is obsolete now: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#differences-in-default-jsonserializer-behavior-compared-to-newtonsoftjson
78+
/*
79+
* TODO: Must be removed
80+
* This code is obsolete now: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#differences-in-default-jsonserializer-behavior-compared-to-newtonsoftjson
8181
.AddJsonFormatters() // See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#content-formatting
8282
.AddJsonOptions(options =>
8383
{
@@ -91,16 +91,16 @@ public void ConfigureServices(IServiceCollection services)
9191
options.SerializerSettings.Formatting = Formatting.None;
9292
#endif
9393
})*/
94-
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
94+
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
9595

9696
services
9797
.AddAutoMapper(typeof(Startup)) // Check out Configuration/AutoMapperProfiles/DefaultProfile to do actual configuration. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#automapper
9898
.AddSwagger(); // Check out Configuration/DependenciesConfig.cs/AddSwagger to do actual configuration. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#documenting-api
9999

100-
services.AddRouting();
101-
services.AddControllers();
102-
services.AddHealthChecks();
103-
}
100+
services.AddRouting();
101+
services.AddControllers();
102+
services.AddHealthChecks();
103+
}
104104

105105
/// <summary>
106106
/// Configure Autofac DI-container
@@ -147,10 +147,10 @@ public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
147147
// See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#unhandled-exceptions-handling
148148
app.UseExceptionHandler();
149149

150-
app.UseRouting();
150+
app.UseRouting();
151151

152-
// See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#cross-origin-resource-sharing-cors-and-preflight-requests
153-
app.UseCors(builder => builder
152+
// See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#cross-origin-resource-sharing-cors-and-preflight-requests
153+
app.UseCors(builder => builder
154154
.AllowAnyOrigin()
155155
.AllowAnyMethod()
156156
.AllowAnyHeader());
@@ -159,13 +159,13 @@ public void Configure(IApplicationBuilder app, ILogger<Startup> logger)
159159
.UseOptionsVerbHandler() // Options verb handler must be added after CORS. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#cross-origin-resource-sharing-cors-and-preflight-requests
160160
.UseSwaggerWithOptions(); // Check out Configuration/MiddlewareConfig.cs/UseSwaggerWithOptions to do actual configuration. See: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#documenting-api
161161

162-
app.UseEndpoints(endpoints =>
163-
{
164-
endpoints.MapDefaultControllerRoute();
165-
endpoints.MapHealthChecks(Constants.Health.EndPoint); // TODO: Must be documented: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1
166-
});
162+
app.UseEndpoints(endpoints =>
163+
{
164+
endpoints.MapDefaultControllerRoute();
165+
endpoints.MapHealthChecks(Constants.Health.EndPoint); // TODO: Must be documented: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1
166+
});
167167

168-
logger.LogInformation("Server configuration is completed");
168+
logger.LogInformation("Server configuration is completed");
169169
}
170170
}
171171
}

0 commit comments

Comments
 (0)