SwaggerUI on Azure Functions (.NET 8 Update)

69 views Asked by At

I'm currently updating to .NET 8 (also switching to isolated worker process).

I have an implementation of SwaggerUI based on https://devkimchi.com/2019/02/02/introducing-swagger-ui-on-azure-functions/

I have a controller like this:

public static class SwaggerUiController
{
    [Function("SwaggerUiController")]
    public static async Task<IActionResult> RenderSwaggerUI(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "openapi/swaggerui")]
        HttpRequestData  req, ILogger log)
    {
        const string title = "My title 1";
        const string endpoint = "openapi/openapi.yaml";

        return await ConfigureSwaggerUI(req, title, endpoint);
    }...

With 2 more functions that serve 2 different routes (and have other endpoints).

In my ConfigureSwaggerUI I have:

private static async Task<ContentResult> ConfigureSwaggerUI(HttpRequestData req, string title, string endpoint)
{
    var swaggerUi = new SwaggerUI();

    var openApiInfo = CreateOpenApiInfo(title);
    var routePrefix = req.Url.Host.Contains("localhost") ? "api" : "doc";
    // req.Host = new HostString(Environment.GetEnvironmentVariable("MyApiEnvVariable") ?? "localhost:7071");

    var httpRequestObject = new HttpRequestObject(req);

    var assembly = typeof(SwaggerUI).Assembly;

    var result =
            await swaggerUi
                .AddMetadata(openApiInfo)
                .AddServer(httpRequestObject, routePrefix)
                .BuildAsync(assembly)
                .RenderAsync(endpoint)
                .ConfigureAwait(false);

    return CreateContentResult(result);
}

While updating, I had to change from HttpRequest to HttpRequestData which stops me from setting the Host as per the commented line

// req.Host = new HostString(Environment.GetEnvironmentVariable("MyApiEnvVariable") ?? "localhost:7071");

How could I keep my SwaggerUI functionality intact while updating to .NET 8?

1

There are 1 answers

2
Mason A On BEST ANSWER

The following should append a Host Header to the request.

        httpRequestData.Headers.Add("Host", $"{Environment.GetEnvironmentVariable("MyApiEnvVariable") ?? "localhost:7071"}");