Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@GregorT
Last active December 28, 2017 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GregorT/4070b2956932a1d0aaa7a3fc196b601d to your computer and use it in GitHub Desktop.
Save GregorT/4070b2956932a1d0aaa7a3fc196b601d to your computer and use it in GitHub Desktop.
Converting IActionResult view to javascript file with custom ActionFilterAttribute in Asp.Net Core 2x
namespace yourApplicationNameSpace
{
public class JavascriptOutputAttribute : ActionFilterAttribute
{
private static readonly Regex OpenScriptTag = new Regex(@"^\s*<script[^>]*>", RegexOptions.Compiled);
private static readonly Regex CloseScriptTag = new Regex(@"</script>\s*$", RegexOptions.Compiled);
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
var resp = context.HttpContext.Response;
using (var buffer = new MemoryStream())
{
var realBody = resp.Body;
context.HttpContext.Response.Body = buffer;
context.HttpContext.Response.ContentType = "text/javascript";
await next();
var newResponse = ReformatResponseToJavascriptFile(buffer);
using (var newResponseBuffer = new MemoryStream(Encoding.UTF8.GetBytes(newResponse)))
{
resp.Body = realBody;
await newResponseBuffer.CopyToAsync(realBody);
}
}
}
private static string ReformatResponseToJavascriptFile(MemoryStream buffer)
{
string response;
buffer.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(buffer))
{
response = sr.ReadToEnd();
}
if (OpenScriptTag.IsMatch(response) && CloseScriptTag.IsMatch(response))
{
response = OpenScriptTag.Replace(response, string.Empty);
response = CloseScriptTag.Replace(response, string.Empty);
}
return response;
}
}
}
@GregorT
Copy link
Author

GregorT commented Dec 28, 2017

how to use it:

[JavascriptOutput]
public IActionResult MyDynamicJavascriptFile()
{
return View();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment