.NET Core: Dynamically Return Style Sheets with Web API

If you have a need to dynamically return a stylesheet to the UI here’s a quick tutorial on how to do it.

Header Template

<link rel="stylesheet" href="/api/style/style.css" />

C# Web API

    [Route("api/[controller]")]
    public class StyleController : Controller
    {
        [HttpGet("style.css")]
        public async Task<IActionResult> GetBrandCSSAsync() {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();

            // get brand from config
            string brandType = config["Brand"];

            string filePath = @"Styling\";
            filePath = $"{filePath}{brandType}.css";

            // load custom css into string variable
            string fileContents = string.Empty;

            using (StreamReader sr = new StreamReader(filePath)) {
                // Read the stream to a string, and write the string to the console.
                fileContents = sr.ReadToEnd();
            }            
            
            return Content(fileContents, "text/css");
        }
    }