Skip to content

Instantly share code, notes, and snippets.

@nadais
Last active October 27, 2022 08:56
Show Gist options
  • Save nadais/d8aa732c5fdef43448bb71a7d458dc15 to your computer and use it in GitHub Desktop.
Save nadais/d8aa732c5fdef43448bb71a7d458dc15 to your computer and use it in GitHub Desktop.
Example to refactor on not use else keyword
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