Last active
October 27, 2022 08:56
-
-
Save nadais/d8aa732c5fdef43448bb71a7d458dc15 to your computer and use it in GitHub Desktop.
Example to refactor on not use else keyword
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Example; | |
public class ApiKeyMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
private const string APIKEY = "XApiKey"; | |
public ApiKeyMiddleware(RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task InvokeAsync(HttpContext context) | |
{ | |
if (context.Request.Headers.TryGetValue(APIKEY, out | |
var extractedApiKey)) | |
{ | |
var appSettings = context.RequestServices.GetRequiredService<IConfiguration>(); | |
var apiKey = appSettings.GetValue<string>(APIKEY); | |
if (apiKey.Equals(extractedApiKey)) | |
{ | |
await _next(context); | |
} | |
else | |
{ | |
context.Response.StatusCode = 401; | |
await context.Response.WriteAsync("Unauthorized client"); | |
} | |
} | |
else | |
{ | |
context.Response.StatusCode = 401; | |
await context.Response.WriteAsync("Api Key was not provided "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment