C# 10 File Scoped Namespaces - How to Migrate Your Project

One of the nice new features in C# 10 is file scoped namespaces.  It clears some of the cruft and provides more horizontal space for code instead of an extra indent.  If you are using Visual Studio 2022 or later you have a couple of nice options to apply this change at a page or project level.

At a page level, you can simply add a semi-colon at the end of your traditional using statement:

namespace ApiKeyAuthentication
{
    ...
}

VS will auto refactor this to

namespace ApiKeyAuthentication;

and remove the curly braces and indentation.

If you want to apply this to your entire project, follow these steps:

  1. Create a new file in your project root called .editorconfig (or use the existing file)
  2. Under Code Style search for namespace and select File Scoped
  3. Go to one of your traditional namespace declarations, right-click it and select "Quick Actions and Refactorings". You will see a list of all refactoring actions available, and one of them will be "Convert to file-scoped namespace". At the bottom, select Project and you’ll see a preview of the changes to be made. Then click Apply.
  4. Build your project and ensure there are no errors.

Need a developer, architect or manager? I am available - email me at [email protected]

Adding a custom header to the swagger UI for API authentication

If you need to add a custom HTTP header such as x-api-key to your API calls and want to include this while using the swagger API, you can use the code below and add it to your program.cs file in a .NET Core application to get it working.

builder.Services.AddSwaggerGen(c =>
    {
        c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
        {
            Description = "The API Key to access the API",
            Type = SecuritySchemeType.ApiKey,
            Name = "x-api-key",
            In = ParameterLocation.Header,
            Scheme = "ApiKeyScheme"
        });
        var scheme = new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "ApiKey"
            },
            In = ParameterLocation.Header
        };
        var requirement = new OpenApiSecurityRequirement
        {
            {scheme, new List<string>() }
        };
        c.AddSecurityRequirement(requirement);
    });

On the swagger UI, you will then see an Authorize button that when clicked, allows you to enter the header value and it will be included in your requests.

Full code sample on GitHub - https://github.com/cliffordru/ApiKeyAuthentication

Need a developer, architect or manager? I am available - email me at [email protected]

Implementing API Key Authentication in ASP.NET Core

Recently I was watching Nick Chapsas on YouTube and his tutorial on Implementing API Key Authentication in ASP.NET Core.  He did a very nice job of explaining how to add checking for a HTTP Header value to authenticate calls to your web api.  He touched on adding support for minimal endpoints in .NET core by creating a filter.  Specifically, a class ApiKeyEndpointFilter that will return TypedResults.Unauthorized if the x-api-key is missing or invalid.  This return type does not support a custom unauthorized message.  In order to accomplish that, a new class is needed that implements IResult and IStatusCodeHttpResult.  The class signature looks like: UnauthorizedHttpObjectResult : IResult, IStatusCodeHttpResult

Once you implement, you can then use the following approach to use the filter:

return new UnauthorizedHttpObjectResult("API Key missing"); 

app.MapGet("/", () => "Welcome mini!")
                .AddEndpointFilter<ApiKeyEndpointFilter>();

My full solution is available on GitHub:
https://github.com/cliffordru/ApiKeyAuthentication.git

See UnauthorizedHttpObjectResult.cs for the code needed to return a custom message. 

Tags: unauthorized http objectresult TypedResults with custom message

Need a developer, architect or manager? I am available - email me at [email protected]