Viewing Server Variables in Asp.Net Core

January 02, 2021

In Asp.Net Core, you can view a list of data known as Server Variables. These are available when hosting inside IIS, and they give information about the request call and security.

You can view any one of these by adding some middleware to your Asp.Net Core project:



    app.Use(async (context, next) =>
    {
        var url = context.Features.Get<IServerVariablesFeature>()["URL"];

        await next.Invoke();
    }

You’ll need to be hosting inside IIS, and the code should go in the routing zone.

There is also a helper method for this, meaning you can do this instead:



    app.Use(async (context, next) =>
    {
        string a = context.GetServerVariable("URL");

        await next.Invoke();
    }

I then thought, why not just enumerate all the variables. You can see the list here.

I created a list of these:



    public static class ServerVariables
    {
        public static string[] Variables = new[]
        {
            "UNENCODED\_URL",
            "URL",
            "QUERY\_STRING",
            "REMOTE\_ADDR",
            "ALL\_HTTP",
            "AUTH\_USER",
            "AUTH\_TYPE",
            "REMOTE\_USER",
            "SERVER\_ADDR",
            "LOCAL\_ADDR",
            "SERVER\_PROTOCOL",
            "ALL\_RAW",
            "REMOTE\_HOST",
            "SERVER\_SOFTWARE",
            "HTTP\_RAW",
            "HTTP\_COOKIE"
        };
    }

And then, in the middleware, just looped through them:



            app.Use(async (context, next) =>
            {                
                await context.Response.WriteAsync("<div>");
                foreach (var variable in ServerVariables.Variables)
                {
                    string result = context.GetServerVariable(variable);
                    await context.Response.WriteAsync($"<p>{variable}:    <b>{result}</b></p><br />");
                }

                await context.Response.WriteAsync("</div>");
                await next.Invoke();
            });

Remember that if you run this hosted in Kestrel, you’ll get nothing back.

References

https://docs.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms524602(v=vs.90)



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024