.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
1 |
<link rel="stylesheet" href="/api/style/style.css" /> |
C# Web API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
[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"); } } |